程序找错???请解释为什么???
class mml{
private:
static unsigned int x;
public:
mml(){ x++; }
mml(static unsigned int &) {x++;}
~mml{x--;}
pulic:
virtual mon() {} = 0;
static unsigned int mmc(){return x;}
......
};
class nnl:public mml
{
private:
static unsigned int y;
public:
nnl(){ x++; }
nnl(static unsigned int &) {x++;}
~nnl{x--;}
public:
virtual mon() {};
static unsigned int nnc(){return y;}
......
};代码片断:
mml* pp = new nnl;
..........
delete pp;
A:
基类的析构函数应该为虚函数
virtual ~mml{x--;} 笔试题? C++ Primer上说:如果删除基类指针,则需要允许基类析构函数并清除基类的成员,如果对象实际是派生类型,则没有定义该行为。要保证运行适当的析构函数,基类的析构函数必须为虚函数。
如果析构函数为虚函数,那么通过指针调用,运行那个析构函数将因指针所指对象类型的不同而不同……
so…… the deconstructor of base class should be vitrual. Or when deleting, the object of derive class will not be deleted. 还是不明白!!!! 找书看吧。。。。很基础的东西。。。 子类对象的析构要调用子类的析构函数, 在子类的析构函数里会自动调用父类的析构函数(不需要你自己编写,构造函数同理). 用基类指针指向子类对象时, 为确保delete时调用的是子类的析构函数, 需要在基类的析构函数前加上virtual关键字( 则子类的析构函数会默认成为虚函数, 防入该类的虚表中)
如果你的类不用于继承或多态, 不用使用virtural 问题其实就是多态在C++中如何实现。。。
一个设计原则:
C++基类的析构函数都应该是virtual
页:
[1]