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

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

// 这里将copy构造函数和copy assignment操作符统称为copying函数。
// 1.Copying函数应该确保复制“对象内的所有成员变量”及“所有base class成分”。
// 2.不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,
// 并由两个copying函数共同调用。copy构造函数和copy assignment操作符两个之间的互相调用
// 是没有任何意义的,一个用来构造新的对象,另一个用来给对象赋值。

#include <iostream>
#include <string>

class Customer {
public:
	Customer() {
	}
	Customer(const Customer& rhs) : name_(rhs.name_) {
		// name_ = rhs.name_;  // 不要这样写,效率问题,构造问题,写到初始化列表
	}
	Customer& operator=(const Customer& rhs) {
		name_ = rhs.name_;
		return *this;
	}

private:
	std::string name_;
};

class PriorityCustomer : public Customer {
public:
	PriorityCustomer() {
	}
	PriorityCustomer(const PriorityCustomer& rhs)
		: Customer(rhs), priority_(rhs.priority_) {  // 调用base class的copy构造函数
	}
	PriorityCustomer& operator=(const PriorityCustomer& rhs) {
		Customer::operator=(rhs);  // 对base class成分进行赋值
		priority_ = rhs.priority_;
		return *this;
	}

private:
	int priority_;
};

int main() {
	PriorityCustomer priority_customer;
	PriorityCustomer priority_customer2(priority_customer);
	priority_customer = priority_customer2;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值