1

可能重复:
在 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() 函数。我的错误在哪里?

4

2 回答 2

6

您的编译器正在抱怨,因为这两个函数没有相同的返回类型:其中一个返回 a void,另一个返回 a 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
   }
};

如果你不能改变类Aand B,你可以改变类CandD有一个void Show()方法而不是一个bool Show()方法。

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

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

private:
    B b;
};
于 2012-11-07T08:08:17.313 回答
1

您需要添加一个中间人。就像是:

class C1 : public C{
public:
    virtual bool show(){ /* magic goes here */ }
};

class D: public C1, public B{
....

要调用 Show,您需要以下内容: static_cast<C&>(c).Show();

于 2012-11-07T08:15:36.500 回答