可能重复:
在构造函数中调用虚函数
看看这段代码。在 Base 类的构造函数中,我们可以使用 'this' 指针调用纯虚函数。现在,当我想创建一个指向同一类的类型化指针并将“this”转换为同一类型时。它抛出运行时异常“纯虚函数调用异常”。为什么会这样?
#include <iostream>
using namespace std;
class Base
{
private:
virtual void foo() = 0;
public:
Base()
{
//Uncomment below 2 lines and it doesn't work (run time exception)
//Base * bptr = (Base*)this;
//bptr->foo();
//This call works
this->foo();
}
};
void
Base::foo()
{
cout << "Base::foo()=0" << endl;
}
class Der : public Base
{
public:
Der()
{
}
public:
void foo()
{
cout << "Der::foo()" << endl;
}
};
int main()
{
cout << "Hello World!" << endl;
Der d;
}