【问题标题】:Please help me out why I am getting error?请帮我看看为什么我会出错?
【发布时间】:2021-11-06 05:14:18
【问题描述】:

我不明白为什么Derived 类在覆盖函数fun() 后仍然是抽象的。

这是错误信息:

error: invalid new-expression of abstract class type 'Derived' Base *t = new Derived(a);
error: no matching function for call to 'Base::fun(int&)'int i = t->fun(b);
#include <iostream>
using namespace std;

class Base
{
protected:
    int s;

public:
    Base(int i = 0) : s(i) {}
    virtual ~Base() {}
    virtual int fun() = 0;
};

class Derived: public Base
{
public:
    Derived(int i) : Base(i) {}
    ~Derived() { cout << --s << " "; }
    int fun(int x) { return s * x; }
};

class Wrapper
{
public:
    void fun(int a, int b)
    {
        Base *t = new Derived(a);
        int i = t->fun(b);
        cout << i << " ";
        delete t;
    }
};

int main()
{
    int i, j;
    cin >> i >> j;
    Wrapper w;
    w.fun(i, j);
    return 0;
}

【问题讨论】:

    标签: c++ c++11 visual-c++


    【解决方案1】:

    问题是

    int fun(int x) { return s * x; }
    

    不覆盖

    virtual int fun() = 0;
    

    因为参数列表不同(没有参数与单个int)。如果你写了

    int fun(int x) override { return s * x; }
    

    你应该从 C++11 开始,然后编译器会给你一个错误。

    【讨论】:

    • 谢谢先生 :)
    【解决方案2】:

    函数在基类和派生类之间有两个不同的签名

    virtual int fun() = 0;
    

    然后是派生类

    int fun(int x) { return s * x; }
    

    如果您添加override,它会提醒您注意此错误

    int fun(int x) override { return s * x; }
    

    【讨论】:

    • 谢谢先生 :)
    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2016-10-29
    • 2021-05-26
    相关资源
    最近更新 更多