有基类Customer如下,
-
void logCall(const std::string& funcName);
-
class Customer {
-
public:
-
//...
-
Customer(const Customer& rhs);
-
Customer& operator=(const Customer& rhs);
-
//...
-
-
private:
-
std::string name;
-
};
-
-
Customer::Customer(const Customer & rhs)
-
: name(rhs.name)
-
{
-
logCall("Customer copy constructor");
-
}
-
-
Customer& Customer::operator=(const Customer& rhs)
-
{
-
logCall("Customer copy assignment operator");
-
name = rhs.name;
-
-
return *this;
-
}
-
倘若该类被PrioCustomer类继承,其构造如下,
-
class PrioCustomer: public Customer {
-
public:
-
//...
-
PrioCustomer(const PrioCustomer& rhs);
-
PrioCustomer& operator=(const PrioCustomer& rhs);
-
//...
-
-
private:
-
int priority;
-
};
-
-
PrioCustomer::PrioCustomer(const PrioCustomer & rhs)
-
: priority(rhs.priority);
-
{
-
logCall("PrioCustomer copy constructor");
-
}
-
-
PrioCustomer& PrioCustomer::operator=(const PrioCustomer & rhs)
-
{
-
logCall("PrioCustomer copy assignment operator");
-
-
priority = rhs.priority;
-
-
return *this;
-
}
初看好像该copy构造函数没问题,但这里需要指明的是PrioCustomer类只复制了其自身定义的成员变量,并没有copy基类Customer的成员变量,
其基类Customer的成员变量只是以默认参数初始化之。
正确的构造应该,
-
PrioCustomer::PrioCustomer(const PrioCustomer & rhs)
-
: Customer(rhs),
-
priority(rhs.priority);
-
{
-
logCall("PrioCustomer copy constructor");
-
}
-
-
PrioCustomer& PrioCustomer::operator=(const PrioCustomer & rhs)
-
{
-
logCall("PrioCustomer copy assignment operator");
-
-
Customer::operator=(rhs);
-
priority = rhs.priority;
-
-
return *this;
-
}
阅读(1309) | 评论(0) | 转发(0) |