我正在尝试在 c++ 中探索这个指针。我创建了一个指向类对象的指针并调用了一个函数来删除当前对象,但行为是意外的。
为什么最后一个打印语句的输出是 x= 0 , y= 6。
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 6, int y = 6) { this->x = x; this->y = y; }
void setX(int a) { x = a; }
void setY(int b) { y = b; }
void destroy() { delete this;
}
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test *obj = new Test();
Test objs;
obj->print();
obj->destroy();
obj->print();
return 0;
}