我有一种情况,似乎没有调用构造函数:
#include <iostream> using namespace std; int main () { class yoyo { public: int i; yoyo() { i = 0; cout << "defaultly initialized to 0" << endl; } yoyo (int j) : i(j) { cout << "initialized to " << j << endl; } }; int i; yoyo a; cout << "Hello1,i: " << a.i << endl; yoyo b(5); cout << "Hello2,i: " << b.i << endl; yoyo c = b; /* 1 */ cout << "Hello3,i: " << c.i << endl; return 0; }
输出是:
defaultly initialized to 0 Hello1,i: 0 initialized to 5 Hello2,i: 5 Hello3,i: 5
(注意:Hello2和Hello3之间没有任何内容)
如果我将程序更改为如下所示:
#include <iostream> using namespace std; int main () { class yoyo { public: int i; yoyo() { i = 0; cout << "defaultly initialized to 0" << endl; } yoyo (int j) : i(j) { cout << "initialized to " << j << endl; } }; int i; yoyo a; cout << "Hello1,i: " << b.i << endl; yoyo c; c = b; /* 1 */ cout << "Hello3,i: " << c.i << endl; return 0; }
(唯一的区别在于他标有/ * 1 * /的行)
现在的输出是:
defaultly initialized to 0 Hello1,i: 5 defaultly initialized to 0 Hello3,i: 5
解决方法
如果是
yoyo c = b;
它被称为copy constructor.
而在这种情况下
yoyo c; c = b;
这是被称为copy assignment的操作符.
如果您不提供其中任何一个,编译器将为您生成默认版本.
如果要创建自己的复制构造函数,它可能如下所示:
yoyo(const yoyo& other) : i(other.i) { std::cout << "copy constructor initialized\n"; }
复制赋值运算符如下所示:
yoyo& operator=(const yoyo& other) { i = other.i; return *this; }
当然,它们都在类定义中定义.