【发布时间】:2018-04-01 16:23:31
【问题描述】:
我很难理解默认的复制构造函数和默认的 operator= 在 C++ 中是如何工作的。
在下面的程序中,我不明白为什么最后一行 c0 = b2; cout <<endl; 打印出 32944 。
-operator= 是否定义了复制构造函数?如果不是,它的行为如何?在这种情况下,似乎 b0 在分配给 c0 时使用了复制构造函数:
C(const B& x) : B(x), a(1){z=0; cout <<"9";}
-语句c0 = b2;是如何使用A类的operator=(结果末尾的44)的?
#include <iostream>
using namespace std;
class A{
public:
A(){x=0; cout << "1";}
A(int t) {x=t; cout << "2";}
A(const A& a) {x=a.x; cout << "3";}
const A& operator=(const A& a) {x=a.x; cout << "4"; return *this;}
protected:
int x;
};
class B{
public:
B(const A& a=A()) : y(a) { cout << "5";}
B(const A& b, int u){y=b; k=u; cout << "6";}
protected:
A y; int k;
};
class C : public B{
public:
C(int t=1) {z=t; cout <<"7"; }
C(A x) : B(x) {z=0; cout <<"8";}
C(const B& x) : B(x), a(1){z=0; cout <<"9";}
protected:
A a; int z;
};
int main(){
B b2; cout << endl;
C c0; cout <<endl;
c0 = b2; cout <<endl;
return 0;
}
【问题讨论】:
-
默认的复制分配运算符基本上是按成员分配的。
c0的所有成员都从C(b2)创建的临时对象的各自成员中分配。 -
没有运算符可以将
B分配给C。但是C有一个来自B("9") 的隐式构造函数,所以赋值c0 = b2调用这个隐式构造函数,然后使用C的默认复制赋值。默认复制分配复制C的两个A成员,这解释了输出末尾的“44”。 -
@pschill 为什么在 44 之前调用 9。它应该复制元素而不是打印 9
-
@M. Iduoad 正如我所说,它首先调用打印 9 的构造函数。然后将新构造的对象分配给 c2,打印 44。您可以使用调试器并逐步执行所有函数调用,然后它就变得更清晰了。
标签: c++ inheritance constructor copy-constructor default-copy-constructor