C++覆盖具有与基类不同的返回类型的函数

标签 c++ inheritance overriding

<分区>

Possible Duplicate:
it is possible to change return type when override a virtual function in C++?

我遇到错误:

error: conflicting return type specified for âvirtual bool D::Show()
7: error: overriding âvirtual void A::Show()"

当我编译我的代码时。代码是:

class A
{
       public:  
       virtual void Show()
       {
        std::cout<<"\n Class A Show\n";
       }
};

class B :  public A
{
    public:
    void Show(int i)
    {
            std::cout<<"\n Class B Show\n";
    }
};

class C
{
    public:
    virtual bool Show()=0;
};

class D :public C, public B
{
    public:
        bool Show(){
            std::cout<<"\n child Show\n";
            return true;}
};

int main()
{
    D d;
    d.Show();
    return 0;
}

我想使用类 C 中的 Show() 函数。我的错误在哪里?

最佳答案

您的编译器报错是因为这两个函数没有相同的返回类型:其中一个返回 void 而另一个返回 bool。您的两个函数应该具有相同的返回类型

你应该有

class A {
   public:  
   virtual bool Show() {
      std::cout<<"\n Class A Show\n";
      return true; // You then ignore this return value
   }
};

class B :  public A {
   public:
   bool Show(int i) {
      std::cout<<"\n Class B Show\n";
      return true; // You then ignore this return value
   }
};

如果您不能更改类 AB,您可以将类 CD 更改为有一个 void Show() 方法而不是 bool Show() 方法。

如果你不能做任何这些事情,你可以使用composition over inheritance : 在你的 D 函数中有一个 B 类型的成员,而不是从它继承:

class D : public C {
public:
    bool Show() {
        std::cout<<"\n child Show\n";
        return true;
    }
    void ShowB() {
        b.Show();
    }

private:
    B b;
};

关于C++覆盖具有与基类不同的返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13265522/

相关文章:

flutter - 如何根据dartlang中的扩展类设置类型定义

ios - 继承属性,在从只读继承的属性中读写时不合成setter

java - 覆盖与隐藏 Java - 困惑

java - 在编写 Java 代码时,我们真的需要 @Override 等吗?

c++ - int/counter 的奇怪行为

c++ - 如何删除结构数组的元素?

c++ - 使用简单\非侵入式数据模型的 C++ 中的 XML 数据绑定(bind)

python - 如何根据指针地址获取指针内容

javascript - 继承nodejs

overriding - Magento:我们如何覆盖企业文件(企业版)?