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

例子:

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.

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


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值