拷贝构造函数 & 拷贝赋值运算符

一、拷贝构造函数

1. 形式

class A {
public: 
	// ... 
	A(const A &);			// 拷贝构造函数 
}; 

2. 合成拷贝构造函数

  • 编译器总会为我们合成一个拷贝构造函数,即使我们定义了其他构造函数。

3. 拷贝构造函数不应该是explicit的

  • 拷贝构造函数在必要时可以被隐式地使用。

4. 拷贝初始化

①用=定义对象

string s1 = s;
string s2 = "hello";
string s3 = string(10, 'c');

②传递参数(形参为非引用类型)

③函数返回一个非引用类型的对象

④用花括号初始化一个数组中的元素或一个聚合类中的成员

二、拷贝赋值运算符

1. 形式

class A {
public: 
	// ... 
	A& operator=(const A &);			// 赋值运算符 
}; 

2. 合成拷贝赋值运算符

  • 编译器会为我们生成一个合成拷贝赋值运算符,如果该类未定义自己的拷贝赋值运算符。

3. 与拷贝构造函数的区别

class string {
public:
	// ...
	string(const string &);
	string& operator=(const string &);
}; 

string s;	
string ss = "hello";		// 拷贝构造函数 
s = ss;						// 拷贝赋值运算符 

  

猜你喜欢

转载自www.cnblogs.com/xzxl/p/8975679.html