可能重复:在构造函数中调用虚函数
看一下这段代码。在基类的构造函数中,我们可以使用'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;
}
this->foo()
能够正常工作,而通过强制类型转换调用则失败了。 - Agnel Kurian