#include <iostream>
using namespace std;
class A
{
public:
int x;
A(){x= 30; cout << "A's constructor called " << endl;}
A(const A& obj) { cout<<"A's copy constructor called " <<endl; }
};
class B
{
public:
static A sample;
B() { cout << "B's constructor called " << endl; }
static A getSample() { return sample; }
};
A B::sample;
int main()
{
A one;
A two = B::getSample();
cout<<B::sample.x<<endl;
cout<<one.x<<endl;
cout<<two.x<<endl;
return 0;
}
上面的代码输出:
A's constructor called
A's constructor called
A's copy constructor called
30
30
-1032819680
为什么不复制构造函数将 x 的值复制到 B::getSample()
.换句话说,虽然B::getSample()=30
,为什么two.x
-1032xxxxxx
?
您已经定义了自己的复制构造函数,该构造函数不复制 x
的值。所以它没有初始化。
行为是正确的,复制构造器被调用为它们应该的样子......但:
如果你想two.x
30
,你需要在你的复制构造函数中复制x
值...在您的代码中并非如此。您只是打印A's copy constructor called
但复制构造函数不起作用。
只需将其更改为
A(const A& obj)
{
cout<<"A's copy constructor called " <<endl;
x = obj.x; // added!
}
然后,程序显示:
A's constructor called
A's constructor called
A's copy constructor called
30
30
30
两个是使用您定义的复制构造函数初始化的。在这个定义中,你没有给x赋任何值。这就是它打印垃圾的原因。
,如果未定义默认的复制构造函数,编译器将创建一个默认的复制构造函数。这将执行浅拷贝,这意味着使用标准赋值运算符 ('='( 单独复制类的每个成员。
x=obj.x;
由于这正是您无论如何都会要做的事情,因此真的没有理由覆盖。
如果您有一个没有动态分配的内存(或指针(的简单类,则此方法非常有效。但是,如果要复制指针(指向数据块(,则浅表复制不起作用。这是因为赋值运算符只是复制指针的地址,而不分配任何内存或复制指向的内容。