C++复制对象时勿忘每一部分

现看这样一个程序:

void logCall(const string&  funcname) //标记记录
{
    cout <<funcname <<endl;
}

class Custom
{
    public:
    Custom(const Custom& p):name(p.name)
    {
        logCall("Custom copy constructor!")
    }
    Custom& operator=(const Custom& p)
    {
        logCall("Custom copy assignment operator!")
        name=p.name;
        return *this;
    }
    private :
        string  name;
};

class PriorityCustom:public Custom   //派生类
{
    public:
    PriorityCustom(const PriorityCustom& p):priority(p.priority)
    {
        logCall("PriorityCustom copy constructor!")
    }
    PriorityCustom& operator=(const PriorityCustom& p)
    {
        logCall("PriorityCustom copy assignment operator!")
        priority=p.priority;
        return *this;
    }
    private :
        string  priority;
};

这样一看,藐视程序该做的赋值工作都做了,PriorityCustom的copy函数好像把要复制的工作都做了。

错!请再看一眼。

这样复制的话就有派生类的内容被复制了,而基类的内容却没有复制过去。因为这个复制过程没有调用过基类的copy函数,这样做的话复制完基类内容将是初始化状态。

怎么做呢?派生类复制过程确保基类copy函数也被调用。

class PriorityCustom:public Custom   //派生类
{
    public:
    PriorityCustom(const PriorityCustom& p):Custom(p),priority(p.priority)
    {
        logCall("PriorityCustom copy constructor!")
    }
    PriorityCustom& operator=(const PriorityCustom& p)
    {
        logCall("PriorityCustom copy assignment operator!")
        Custom::operator=(p);
        priority=p.priority;
        return *this;
    }
    private :
        string  priority;
};

注意:

当你写一个copying函数,请确保:

1、复制所有local成员变量。

2、调用所有基类内的适当copying函数。

原文地址:https://www.cnblogs.com/kane0526/p/3611881.html