- #include <iostream.h>
- class CExample
- {
- int m_nTest;
- public:
- CExample(int x):m_nTest(x) //带参数构造函数
- {
- cout << "constructor with argument/n";
- }
- CExample(const CExample & ex) //拷贝构造函数
- {
- m_nTest = ex.m_nTest;
- cout << "copy constructor/n";
- }
- CExample& operator = (const CExample &ex)//赋值函数(赋值运算符重载)
- {
- cout << "assignment operator/n";
- m_nTest = ex.m_nTest;
- return *this;
- }
- void myTestFunc(CExample ex)
- {
- }
- };
- int main()
- {
- CExample aaa(2);
- CExample bbb(3);
- bbb = aaa;
- CExample ccc = aaa;
- bbb.myTestFunc(aaa);
- return 0;
- }
#include <iostream.h> class CExample { int m_nTest; public: CExample(int x):m_nTest(x) //带参数构造函数 { cout << "constructor with argument/n"; } CExample(const CExample & ex) //拷贝构造函数 { m_nTest = ex.m_nTest; cout << "copy constructor/n"; } CExample& operator = (const CExample &ex)//赋值函数(赋值运算符重载) { cout << "assignment operator/n"; m_nTest = ex.m_nTest; return *this; } void myTestFunc(CExample ex) { } }; int main() { CExample aaa(2); CExample bbb(3); bbb = aaa; CExample ccc = aaa; bbb.myTestFunc(aaa); return 0; }
看这个例子的输出结果:
constructor with argument // CExample aaa(2);
constructor with argument // CExample bbb(3);
assignment operator // bbb = aaa;
copy constructor // CExample ccc = aaa;
copy constructor // bbb.myTestFunc(aaa);
第一个输出: constructor with argument // CExample aaa(2);
第二个输出:constructor with argument // CExample bbb(3);
第三个输出: assignment operator // bbb = aaa;
第四个输出: copy constructor // CExample ccc = aaa;
这两个得放到一块说。 肯定会有人问为什么两个不一致。原因是, bbb对象已经实例化了,不需要构造,此时只是将aaa赋值给bbb,只会调用赋值函数, 但是ccc还没有实例化,因此调用的是拷贝构造函数,构造出ccc,而不是赋值函数
第五个输出: copy constructor // bbb.myTestFunc(aaa);
实际上是aaa作为参数传递给bbb.myTestFunc(CExample ex), 即CExample ex = aaa;和第四个一致的, 所以还是拷贝构造函数,而不是赋值函数
通过这个例子, 我们来分析一下为什么拷贝构造函数的参数只能使用引用类型。
看第四个输出: copy constructor // CExample ccc = aaa;
构造ccc,实质上是ccc.CExample(aaa); 我们假如拷贝构造函数参数不是引用类型的话, 那么将使得 ccc.CExample(aaa)变成aaa传值给ccc.CExample(CExample ex),即CExample ex = aaa,因为 ex 没有被初始化, 所以 CExample ex = aaa 继续调用拷贝构造函数,接下来的是构造ex,也就是 ex.CExample(aaa),必然又会有aaa传给CExample(CExample ex), 即 CExample ex = aaa;那么又会触发拷贝构造函数,就这下永远的递归下去。
所以绕了那么大的弯子,就是想说明拷贝构造函数的参数使用引用类型不是为了减少一次内存拷贝, 而是避免拷贝构造函数无限制的递归下去。
所以, 拷贝构造函数是必须要带引用类型的参数的, 而且这也是编译器强制性要求的