【发布时间】:2015-02-06 02:56:07
【问题描述】:
假设两个对象(同一个类)已经被初始化了。
现在,您可以: 对象2 = 对象1;
在 Java 中,Object1 和 Object2 现在都指向同一个内存位置。
在 C++ 中会发生什么?
#include <iostream>
using namespace std;
class X {
public:
X() {
cout << "Default Constructor called\n";
i = 0;
}
X(int i) {
cout << "Parameterized Constructor called\n";
this->i = i;
}
X (const X& x) {
cout << "Copy Constructor called\n";
i = x.getI();
}
~X() {
cout << "Destructor called\n";
}
int getI() const {
return i;
}
private:
int i;
};
void main() {
cout << "\nLine-1\n\n";
X x1(1); // On Stack
cout << "\nLine-2\n\n";
X* x2 = new X(2); // On Heap
cout << "\nLine-3\n\n";
X x3(x1);
cout << "\nLine-4\n\n";
X* x4 = new X(x1);
cout << "\nLine-5\n\n";
X x5 = x1;
cout << "\nLine-6\n\n";
x5 = x3;
cout << "\nLine-7\n\n";
X x6 = *x2;
cout << "\nLine-8\n\n";
*x2 = *x4;
cout << "\nLine-9\n\n";
*x4 = x3;
cout << "\nLine-10\n\n";
}
如您所见,每当我执行 createdObj1 = createdObj2 时,都不会调用任何构造函数。
【问题讨论】:
-
它们是如何初始化的? (例如,使用新的,还是堆栈分配的?)
-
在堆栈上,我的兄弟。
-
复制赋值运算符被调用。编译器默认提供一个。
-
@Ben Voigt:这将我们带到下一个问题。我编写了自己的复制构造函数并有一个打印语句来知道它何时被调用,但它从未被调用过。
-
main()应返回int。
标签: c++