读书人

构造函数析构函数 虚函数解决思路

发布时间: 2012-11-05 09:35:12 作者: rapoo

构造函数析构函数 虚函数
为什么在构造函数和析构函数中不能调用虚函数,最好举出反例(附有代码更好)?

[解决办法]
代码很简单自己写个验证下就可以了。
具体原因参考深度探索C++对象模型,虚指针的初始化是在构造函数里,在调用到基类的构造函数时,派生类还不是一个完整的对象,派生类的虚指针还没完全初始化,没完全初始化的指针怎么能检索到虚表里相应的项?析构函数同理,先析构派生类对象再析构基类对象,到了基类对象的析构时,派生类对象已经不完整了。
说错了楼下斧正。。
[解决办法]
构造函数和析构函数中可以调用虚函数,但不能实现多态

随便写个程序测试下就知道了

[解决办法]

C/C++ code
class A{public:    A()    {        print();    }    virtual void print()    {        cout<<"A"<<endl;    }};class B:public A{public:    B()    {        print();    }    virtual void print()    {        cout<<"B"<<endl;    }};int main(){B b;return 0;}
[解决办法]
C++标准如是说:12.7
4 Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2).
When a virtual function is called directly or indirectly from a constructor (including the mem-initializer or
brace-or-equal-initializer for a non-static data member) or from a destructor, and the object to which the
call applies is the object under construction or destruction, the function called is the one defined in the
constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived
from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived
object (1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expression
refers to the object under construction or destruction but its type is neither the constructor or destructor’s
own class or one of its bases, the result of the call is undefined. [ Example:
C/C++ code
struct V {virtual void f();virtual void g();};struct A : virtual V {virtual void f();};struct B : virtual V {virtual void g();B(V*, A*);};struct D : A, B {virtual void f();virtual void g();D() : B((A*)this, this) { }};B::B(V* v, A* a) {f(); // calls V::f, not A::fg(); // calls B::g, not D::gv->g(); // v is base of B, the call is well-defined, calls B::ga->f(); // undefined behavior, a’s type not a base of B} 

读书人网 >C++

热点推荐