这篇博客参考了:http://soft-app.iteye.com/blog/922040
上面的博客讲的比较详细,解释了复制构造函数和赋值函数的区别,在这里通过相关代码解释复制构造函数和赋值函数的区别,还有需要注意初始化时的隐式类型转换。
上面的博客讲的比较详细,解释了复制构造函数和赋值函数的区别,在这里通过相关代码解释复制构造函数和赋值函数的区别,还有需要注意初始化时的隐式类型转换。
#include <iostream>
using namespace std;
class test
{
public:
test() // 1. 默认构造函数。
{
cout << "default consturctor" << endl;
}
test(int i) // 2. 带参数的构造函数。
{
a = i;
cout <<"test(int i)" << endl;
}
test(const test & other) // 3. 复制构造函数。
{
a = other.a;
cout << "copy constructor" << endl;
}
test& operator=(const test& other) // 4. 赋值函数。
{
a = other.a;
cout << "assignment" << endl;
return *this;
}
private:
int a;
};
int main(int argc, char* argv[])
{
// 1.测试一
test t1; // 调用t1的默认构造函数;
test t2 = t1; // 调用t2的复制构造函数,因为在这里t2属于实例化时期,所以不是赋值函数
t2 = t1; // 调用t2的赋值函数,因为这里t2实例化过程已经完成,所以调用的是赋值函数。
test t3(t1); // 调用t3的复制构造函数,这里t3属于实例化时期。
test t4 = t3 = t2; // 调用t3的赋值函数,调用t4的复制函数。
// 2.测试二
test a = 20; // 调用带int参数的构造函数,这里存在内置数据类型向类类型的隐式转换。
test b = a; // 调用b的复制构造函数。
return 0;
}