抽象类型 "NumericQuestion" 的对象在 C++ 中是不允许的

object of abstract type "NumericQuestion" is not allowed in c++

本文关键字:C++ 不允许 对象 抽象类 NumericQuestion 抽象 类型      更新时间:2023-10-16

此外,这段代码到底在做什么?

const int MAX_QUESTIONS = 100;
Question* questions[MAX_QUESTIONS];
questions[numQuestions++] = createQuestion("How many degrees are there in a full circle?", 360);

Question* createQuestion(const char question[], const double answer)
{
    NumericQuestion* nq = new NumericQuestion(question, answer);
        return nq;
}

非常感谢。我真的需要你的帮助向我解释

编辑:这是问题的声明

class Question
{
    char *q;
protected:
    void writeQuestion(ostream& ostr) const;
public:
    Question(const char question[])
    {
        int n = strlen(question);
        q =  new char[n];
        strcpy(q, question);
        cout << q;
        }
    void askQuestion() const;
    virtual void getAnswer();
    virtual bool isCorrect() const=0;
};

编辑:NumericQuestion 的声明

class NumericQuestion : public Question
{
    double ans, geta;
public:
    NumericQuestion(const char question[], const double answer): Question(question)
    {
        ans = answer;
        getAnswer();
    }
    void getAnswer()
    {
        cout << "Answer: ";
        cin >> geta;
        isCorrect();
        }
    bool isCorrect()
    {
        return ((geta==ans)? true : false);
    }
};

堆栈溢出不允许我发布这么多代码

您需要在NumericQuestion:中将isCorrect()声明为const

bool isCorrect() const  // <--- add const keyword here

原因是const是方法签名的一部分,就像它的名称和参数一样。isCorrect() const是一个不同于名为isCorrect()的非常量函数的方法。

当您看到一个带有=0的虚拟方法时,这意味着该方法是"纯虚拟的"。基类通常不会指定实现,但在实例化任何派生类之前,必须定义一个实现。