Error: pure virtual method called - terminate called without an active exception - Aborted

前端 未结 4 491
清酒与你
清酒与你 2020-12-16 20:31

In my A.h file:

class A{
  private:
    unsigned short PC;
  public:
    A():PC(0){}
    virtual ~A(){}
    virtual void execute(unsigned short PC)=0;
};


        
相关标签:
4条回答
  • 2020-12-16 20:36
    int main(int args, char**argv){
        A *a;
        B b; // wrong
        a = &b; // wrong
        Functions f;
        f.run(a);
        return 1;
    }
    

    you can do this :

    int main(int args, char**argv){
        A *a = new B;
        //B b;
        //a = &b;
        Functions f;
        f.run(a);
        return 1;
    }
    
    0 讨论(0)
  • 2020-12-16 20:40

    Usually you get this error when call your virtual function from constructor or destructor. Check that that is not the case.

    (I assume that your demo code is not complete).

    0 讨论(0)
  • 2020-12-16 20:42

    Don't know what you're doing but this, which is basically what you're showing us, except that is simplified and actually compiling, runs without any problems:

    #include <iostream>
    
    class A
    {
    public:
       virtual ~A() {}
       virtual void execute() = 0;
    };
    
    class B: public A
    {
    public:
       virtual void execute() {std::cout << "B::execute" << std::endl;}
    };
    
    void execute(A* a)
    {
       a->execute();
    }
    
    int main()
    {
       A* a;
       B b;
       a = &b;
    
       execute(a);
    
       return 0;
    }
    
    0 讨论(0)
  • 2020-12-16 20:51

    You wrote B() constructor without paranthesis , plus you have 2 B() default constructors, plus one of them is virtual(not good), plus when you execute a->execute, again you need paranthesis with an argument, because it is a function:

    Try this:

    #include <iostream>
    using namespace std;
    
    class A{
    private:
    unsigned short PC;
    public:
    A():PC(0){}
    virtual ~A(){}
    virtual void execute(unsigned short PC)=0;
    };
    
    
    class B:public A{
    private:
        int status;
        bool exe;
    public:
    B():status(0),exe(false){}
    //virtual B(){}
    void execute (unsigned short PC);
    };
    
    
    
    void B::execute (unsigned short PC){
    cout << "Run";
    }
    
    
    
    class Functions{
    public: int status;
    Functions():status(1){} // this is a constructer
    void run(A *a);
    };
    
    
    void Functions::run (A *a){
    a->execute(1);
    }
    
    
    int main(int args, char**argv){
    A *a;
    B b;
    a = &b;
    Functions f;
    f.run(a);
    return 1;
    }
    
    0 讨论(0)
提交回复
热议问题