相关疑难解决方法(0)

调用纯虚函数

可能重复:
在构造函数内调用虚函数

看看这段代码.在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!" …
Run Code Online (Sandbox Code Playgroud)

c++ function pure-virtual

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

function ×1

pure-virtual ×1