Chinaunix首页 | 论坛 | 博客
  • 博客访问: 299337
  • 博文数量: 94
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 202
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-08 20:07
文章分类

全部博文(94)

文章存档

2017年(19)

2016年(30)

2015年(12)

2014年(33)

我的朋友

分类: LINUX

2017-05-16 09:54:16

有基类Customer如下,

点击(此处)折叠或打开

  1. void logCall(const std::string& funcName);
  2. class Customer {
  3. public:
  4.     //...
  5.     Customer(const Customer& rhs);
  6.     Customer& operator=(const Customer& rhs);
  7.     //...

  8. private:
  9.     std::string name;
  10. };

  11. Customer::Customer(const Customer & rhs)
  12.     : name(rhs.name)
  13. {
  14.     logCall("Customer copy constructor");
  15. }

  16. Customer& Customer::operator=(const Customer& rhs)
  17. {
  18.     logCall("Customer copy assignment operator");
  19.     name = rhs.name;

  20.     return *this;
  21. }

倘若该类被PrioCustomer类继承,其构造如下,

点击(此处)折叠或打开

  1. class PrioCustomer: public Customer {
  2. public:
  3.     //...
  4.     PrioCustomer(const PrioCustomer& rhs);
  5.     PrioCustomer& operator=(const PrioCustomer& rhs);
  6.     //...

  7. private:
  8.     int priority;
  9. };

  10. PrioCustomer::PrioCustomer(const PrioCustomer & rhs)
  11.     : priority(rhs.priority);
  12. {
  13.     logCall("PrioCustomer copy constructor");
  14. }

  15. PrioCustomer& PrioCustomer::operator=(const PrioCustomer & rhs)
  16. {
  17.     logCall("PrioCustomer copy assignment operator");

  18.     priority = rhs.priority;

  19.     return *this;
  20. }

初看好像该copy构造函数没问题,但这里需要指明的是PrioCustomer类只复制了其自身定义的成员变量,并没有copy基类Customer的成员变量,
其基类Customer的成员变量只是以默认参数初始化之。

正确的构造应该,

点击(此处)折叠或打开

  1. PrioCustomer::PrioCustomer(const PrioCustomer & rhs)
  2.     : Customer(rhs),
  3.      priority(rhs.priority);
  4. {
  5.     logCall("PrioCustomer copy constructor");
  6. }

  7. PrioCustomer& PrioCustomer::operator=(const PrioCustomer & rhs)
  8. {
  9.     logCall("PrioCustomer copy assignment operator");

  10.     Customer::operator=(rhs);
  11.     priority = rhs.priority;

  12.     return *this;
  13. }

阅读(1256) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~