C++为什么类的成员函数中(复制构造函数,赋值操作符等)可以有貌似类的对象访问类的私有成员的用法?

2023-11-15

例子:

class Human
{
public:
    //default constructor
    Human():IdentifierID("123456"),Name("linzhiling"),birthDay(){ std::cout<<"Defaulted Constructor of Human is called"<<std::endl; }
    //copy control
    //copy constructor
    Human(Human &m):IdentifierID(m.IdentifierID),Name(m.Name) { std::cout<<"copy control of Human is called"<<std::endl;}
    // assign operator
    Human& operator=(Human& h){ IdentifierID = h.IdentifierID;  Name = h.Name;  std::cout<<"assign operator of Human is called"<<std::endl;}
    
    //destructor
    virtual ~Human() { std::cout<<"destructor of Human is called"<<std::endl; }

    std::string getName() { return Name;}
protected:
    std::string IdentifierID;
    std::string Name;
    Date birthDay;
    std::string location;
    unsigned height;   // cm
    unsigned weight;
    unsigned educatedLevel;   //0: less than small school 1: small school 2: middle school 3: master 4:graduate 5: phd
    std::string occupation;
    unsigned relationState;   //0: single  1: has girlfriend or boyfriend 2: married 3:divorced

private:
    std::string Name2;
};


可以看到上面复制控制函数和赋值操作符中都有疑似类对象访问类的非共有成员用法:

Human(Human &m):IdentifierID(<span style="color:#ff0000;">m.IdentifierID</span>),Name(<span style="color:#ff0000;">m.Name</span>) { std::cout<<"copy control of Human is called"<<std::endl;}
Human& operator=(Human& h){ IdentifierID = <span style="color:#ff0000;">h.IdentifierID</span>;  Name = <span style="color:#ff0000;">h.Name</span>;  std::cout<<"assign operator of Human is called"<<std::endl;}

m和h 为类的对象, 确使用了. 操作符访问了类的非公有(protected)成员,  很奇怪?


解释:

The definition of a member function is within the scope of its enclosing class. The body of a member function is analyzed after the class declaration so that members of that class can be used in the member function body, even if the member function definition appears before the declaration of that member in the class member list. 

//When you see the first senctence of ths above sentences, you must have know that the member function belong to the class, but //not an object of the class.

翻译过来,大意就是类的成员函数是定义在类的作用域中的,是属于类型的,而不是某个对象所有,或者可以说,所以类的对象共有这些成员函数


所以类的成员函数中可以访问类的所有对象的所有成员


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++为什么类的成员函数中(复制构造函数,赋值操作符等)可以有貌似类的对象访问类的私有成员的用法? 的相关文章

随机推荐