现在的位置: 首页 > 综合 > 正文

类成员函数可以访问相同类对象的私有对象

2013年08月26日 ⁄ 综合 ⁄ 共 709字 ⁄ 字号 评论关闭

今天在学习c++ copying函数的时候,了解到这个问题:类成员函数可以访问相同类对象的私有对象;
下面这个例子是很好的copying函数,有很多细节。
实例如下:
class Customer
{
public:
   Customer(const Customer& c):
        _name(c._name)
   {
   }
   Customer& operator=(const Customer& c)
   {
        _name = c._name ;
        return *this ;
   }
private:  
    std::string _name ;
};
class PriorityCustomer : public Customer
{
public:
    PriorityCustomer(const PriorityCustomer& pc):
        Customer(pc),
        _priority(pc._priority)
    {       
    }
    PriorityCustomer& operator=(const PriorityCustomer& pc)
    {
        Customer::operator=(pc);
        _priority = pc._priority;
        return *this ;
    }
private:
    int _priority ; 
};

1. 子类实现copying函数一定要调用父类的copying函数,否则会调用一个父类的默认copying函数,导致问题;
2. 可以用子类对象构造父类;
3. 这个例子说明了另外一个问题,类成员函数可以访问相同类对象的私有成员;

抱歉!评论已关闭.