1.不要忘记复制成员变量
class customer
{public:
customer(const customer & c)
:name(c.name)
{}
customer& operator=(const customer& c)
{
name = c.name;
return *this;
}
private:
std::string name;};
在成员变量中,新增一个Transaction变量,切记要修改,构造函数和拷贝构造,如果不新增编译器不会报错,很难令人察觉。
class customer
{public:
customer(const customer & c)
:name(c.name)
,Transaction(c.Transaction)
{}
customer& operator=(const customer& c)
{
name = c.name;
Transaction = c.Transaction;
return *this;
}
private:
std::string name;
std::string Transaction;
};
2.派生类复制不要忘记基类的成分
错误代码,在复制的时候完全忘记基类成分。
class PriorityCustomer : public customer
{
public:
PriorityCustomer(const PriorityCustomer &p)
:priority(p.priority)
{}PriorityCustomer& operator=(const PriorityCustomer& p)
{
priority = p.priority;
}
private:
int priority;
};
正确代码
class PriorityCustomer : public customer
{
public:
PriorityCustomer(const PriorityCustomer &p)
:customer(p)
,priority(p.priority)
{}PriorityCustomer& operator=(const PriorityCustomer& p)
{
customer::operator=(p);
priority = p.priority;
return *this;
}
private:
int priority;
};