class A;
void fcn( A* );
class A
{
public:
virtual void f()=0;
A() { fcn(this); }
};
class B : A
{
void f() { }
};
void fcn( A* p )
{
p->f();//here, call the version of class A.
}
int main(int argc, char **argv)
{
/*construct object A first, in constructor of class A, it call virtual function f(); theoretically it should call
the version of class B, because it is object B. But at this time, object b has not been fully constructed yet.
That means the virtual function table has not been built up yet. so it actually calls the version of class A,
which cause the error of R6025*/
B b;
return 0;
}
所以结论是在构造函数和析构函数中不要调用虚函数,实际项目中case会比较复杂,往往没有这么容易看出来
本文探讨了在C++中构造函数内调用虚函数导致的问题,特别是在对象尚未完全构建完成时调用虚函数可能导致错误。文章通过具体代码示例解释了为何此时会调用基类的虚函数而非派生类的实现,并总结了避免此类问题的最佳实践。

1239

被折叠的 条评论
为什么被折叠?



