我正在尝试创建两个类,它们的实例一起创建和删除。一个类是另一个类的基础:
class Interface;
class MyClass
{
friend class Interface;
private:
MyClass() {}
public:
static MyClass *NewInstance();
Interface *ControlPanel;
};
class Interface : public MyClass
{
friend class MyClass;
private:
Interface() {}
public:
void Control1() {cout << "control1" << endl;}
void Control2() {cout << "control2" << endl;}
void Control3() {cout << "control3" << endl;}
};
应该创建和删除实例的两个成员函数是:
MyClass *MyClass::NewInstance()
{
MyClass *inst = new MyClass;
inst->ControlPanel = new Interface;
return inst;
}
void DeleteMyClassInstance(MyClass *inst)
{
delete inst->ControlPanel;
inst->ControlPanel = 0;
delete inst;
inst = 0;
}
我成功地将实例创建过程与NewInstance()
创建实例的基类 ( ) 中的函数的使用联系起来。但是删除函数DeleteMyClassInstance()
(inst1
inst1->ControlPanel
int main()
{
MyClass *inst1 = MyClass::NewInstance();
inst1->ControlPanel->Control1();
DeleteMyClassInstance(inst1);
inst1->ControlPanel->Control1();
return 0;
}
但是如果我将删除代码放在主函数中,它可以完美运行(inst1->ControlPanel->Control1()
删除语句之后的语句不起作用,这就是我想要的):
int main()
{
MyClass *inst1 = MyClass::NewInstance();
inst1->ControlPanel->Control1();
delete inst->ControlPanel;
inst->ControlPanel = 0;
delete inst;
inst = 0;
inst1->ControlPanel->Control1();
return 0;
}
我的问题是:为什么将 delete 语句直接放在 main 函数中,而将它们放在单独的函数中并在 main 中使用它却不行?为什么我的DeleteMyClassInstance()
函数中的代码会被编译器忽略?