猜猜看
猜一猜会输出什么结果
- C/C++ code
#include "stdafx.h"#include <iostream>using namespace std;class B{public: virtual ~B() { cout<<"~B();"<<endl; fun(); } virtual void fun() { cout<<"B::fun()"<<endl; }};class D : public B{public: virtual ~D() { cout<<"~D();"<<endl; } virtual void fun() { cout<<"D::fun()"<<endl; }};int _tmain(int argc, _TCHAR* argv[]){ { B * pB = new D(); delete pB; } return 0;}
[解决办法]
1。先子类析构
2. 后基类析构
3.只有对象引用或指针可以发生多态!
结果: ~D(); ~B() B::fun()
[解决办法]
~D();
~B();
B::fun()
[解决办法]
[解决办法]
在析构中调用函数···
真够呛的···
[解决办法]
额 去看看effective c++里面说的吧。不要在构造函数和析构函数里面调用虚函数。
[解决办法]
在构造函数或析构函数中调用虚函数时,不会发生动态绑定,因为此时都是不完整的对象。