#include <iostream>
class A
{
public:
A(int n = 1) : i(n) {}
void Transform(int j)
{
// I want to create a new object and assign that object to "this"
A *obj = new A(j);
delete this;
this = obj;
}
private:
int i;
};
我可以在类 A
的函数 Transform()
中实例化类 A
的新对象并将新对象分配给 this
同时删除由 this
表示的旧对象?
最佳答案
你不能赋值给this
,但你仍然可以用A::Transform()创建的本地对象交换
:this
代表的对象
#include <iostream>
class A
{
public:
A(int n = 1) : i(n) {}
void Transform(int j)
{
A obj(j); // create a new object A
std::swap(*this, obj);
}
private:
int i;
};
关于c++ - 我可以在类定义中实例化当前类的新对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52662855/