假设两个对象(相同类)已经被初始化。
你现在做:
对象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时,都不会调用任何构造函数。
最佳答案
函数operator=()
定义了会发生什么。可以将其定义为成员函数,通常是:
Object & Object::operator=(const Object &other);
如果您不提供这些功能之一,则将提供默认实现,该实现对每个成员变量使用
operator=()
函数。关于c++ - 当我们在C++中分配相同类的Object1 = Object2时,背景发生了什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28357825/