代码之家  ›  专栏  ›  技术社区  ›  Brian R. Bondy

“纯虚拟函数调用”崩溃来自何处?

  •  99
  • Brian R. Bondy  · 技术社区  · 16 年前

    我有时会注意到程序在我的计算机上崩溃,并出现错误:“纯虚拟函数调用”。

    当不能创建抽象类的对象时,这些程序如何编译?

    7 回复  |  直到 16 年前
        1
  •  101
  •   Destructor    9 年前

    here

    class Base
    {
    public:
        Base() { doIt(); }  // DON'T DO THIS
        virtual void doIt() = 0;
    };
    
    void Base::doIt()
    {
        std::cout<<"Is it fine to call pure virtual function from constructor?";
    }
    
    class Derived : public Base
    {
        void doIt() {}
    };
    
    int main(void)
    {
        Derived d;  // This will cause "pure virtual function call" error
    }
    
        2
  •  61
  •   Len Holgate    14 年前
        3
  •  7
  •   Braden    16 年前

        4
  •  0
  •   BCS    16 年前

        5
  •  0
  •   David Lee    12 年前

    template <typename T>
    class Foo {
    public:
      Foo<T>() {};
      ~Foo<T>() {};
    
    public:
      void SomeMethod1() { this->~Foo(); }; /* ERROR */
    };
    

    template <typename T>
    class Foo {
    public:
      Foo<T>() {};
      ~Foo<T>() {};
    
    public:
      void _MethodThatDestructs() {};
      void SomeMethod1() { this->_MethodThatDestructs(); }; /* OK */
    };
    
        6
  •  0
  •   Niki    7 年前

    extern "C" void _RTLENTRY _pure_error_()
    {
        //_ErrorExit("Pure virtual function called");
        throw Exception("Pure virtual function called");
    }
    

        7
  •  -2
  •   1800 INFORMATION    16 年前

    class A
    {
      A *pThis;
      public:
      A()
       : pThis(this)
      {
      }
    
      void callFoo()
      {
        pThis->foo(); // call through the pThis ptr which was initialized in the constructor
      }
    
      virtual void foo() = 0;
    };
    
    class B : public A
    {
    public:
      virtual void foo()
      {
      }
    };
    
    B b();
    b.callFoo();