与基类不同的返回类型的C 覆盖功能

C++ Overriding function with different return type than in base class

本文关键字:覆盖 功能 返回类型 基类      更新时间:2023-10-16

可能的重复:
当覆盖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 Shown";
       }
};
class B :  public A
{
    public:
    void Show(int i)
    {
            std::cout<<"n Class B Shown";
    }
};
class C
{
    public:
    virtual bool Show()=0;
};
class D :public C, public B
{
    public:
        bool Show(){
            std::cout<<"n child Shown";
            return true;}
};
int main()
{
    D d;
    d.Show();
    return 0;
}

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

您的编译器正在抱怨,因为这两个函数没有相同的返回类型:其中一个返回void,另一个返回bool。您的两个功能应具有相同的返回类型

你应该有

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

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

如果您不能做任何这些事情,则可以在 D函数内使用B类型的成员而不是从中继承:

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

您需要添加一个中间人。类似:

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

要致电表演,您将需要类似的东西: static_cast<C&>(c).Show();