吃饭,聊天

2016/08/26 发现共同爱好者,感谢同事

Posted by WangXiaoDong on August 26, 2016

时间:2016年8月26日 天气:大雨


Author:冬之晓:angry:
Email: 347916416@qq.com
MyAppearance: MyAppearance

    今天中午,该吃饭的时候,突然下起了大雨,我记着我自从上次被雨淋了以后。每天都带着伞,但是打开书包才发现,伞没了,晕!
	之后让泉庆帮忙带到饭店。晚上回去的时候,竟然还下着大雨,然后泉庆带我们去吃饭,吃饭的过程和翔宇聊天,发现他也喜欢AGC,
	很少能有都喜欢AGC的朋友,能遇到兴趣相同的同事很高兴!吃完饭后还是泉庆帮忙给我们送到住的地方,非常感谢泉庆!!

条款12:复制对象时勿忘其每一个成分

设计良好的面向对象系统会将对象的内部封装起来,只留两个函数负责对象拷贝,即copy构造函数与copy assignment操作符。编译器会在必要的时候为类创建coping函数,并说明这些“编译器生成版”的行为:将被拷贝对象的所有成员变量都做一份拷贝。

class Date {...};  
class Customer {  
public:  
    ...  
private:  
    string name;  
    Date lastTransaction;  
};  
  
class PriorityCustomer : public Customer {  
public:  
    PriorityCustomer(const PriorityCustomer& rhs);  
    PriorityCustomer& operator=(const PriorityCustomer& rhs);  
private:  
    int priority;  
};  

任何时候,我们承担起“为derived class撰写copying函数“的重大责任必须很小心复制其 base class成分。那些成分旺旺是private的。所以无法直接访问它们,应该让derived class 的copying函数调用相应的base class函数:

PriorityCustomer::PriorityCustomer(const PriorityCustomer &rhs) : Customer(rhs), priority(rhs.priority)  
{  
}  
  
PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer &rhs)   
{  
    Customer::operator=(rhs);  
    priority = rhs.priority;  
    return *this;  
}  

当我们编写一个copying函数的时候,确保基类复制所有local成员变量,子类调用所有基类内的适当的copying函数。

想要避免 copying assignment 操作符和copy 构造函数重复代码,只有一种办法:

建立衣蛾新的成员函数,给两者调用。这个函数往往在private中。并且命名为:init

请记住:

  • copying函数应该确保复制”对象内所有的成员变量“以及”所有base classes成分”

  • 不要尝试以某个copying函数实现另外一个copying函数。应该将共同技能放进第三个函数中。并有两个copying函数共同调用。