【问题标题】:Creating a new function in a derived class with same name but different return type在派生类中创建具有相同名称但返回类型不同的新函数
【发布时间】:2017-01-11 15:18:22
【问题描述】:
//Base.h
Class Base {
    //...
public:
    virtual std::ostream& display(std::ostream& os) const =0;
}

//Derived1.h
Class Derived1 : Base {
    //...
public:
    std::ostream& display(std::ostream&) const;//defined in Derived1.cpp
}
//Derived2.h
Class Derived2 : Derived1{
    //...
public:
    void display(std::ostream&) const;//error here!!!!!!!!!!!!!!!!!!!!
}

我必须使用 void display(std::ostream&) const;因为它在我实验室的说明中,无法更改。 我必须在派生2的显示函数中调用派生1的显示函数,这很简单,我明白这一点。就这样

void Derived2::display(std::ostream& os) const{
    Derived1::display(os);
}

它会像这样在main中调用

Derived2 A;
A.display(std::cout);

Derived2 中的错误是“返回类型与被覆盖的虚函数的返回类型“std::ostream &”不同也不协变”

从我读到的内容来看,这是因为函数的签名(在这种情况下为返回类型)必须与它被覆盖的函数匹配,但我认为我的实验室希望我创建一个新函数而不是覆盖它,但具有相同的姓名?因为我必须在 Derived2 的 display() 中调用 Derived1 的 display()。有什么想法吗?

哦,是的,我试图用 display() 做的事情被认为是重载,而不是覆盖,对吗?

【问题讨论】:

    标签: c++ function oop inheritance pure-virtual


    【解决方案1】:

    你不能这样做,因为返回类型是不是协变的

    我认为您错过了“实验室”的要求。也阅读这些:

    1. Override a member function with different return type
    2. C++ virtual function return type

    顺便说一句,欢迎来到 StackOverflow...确保为您未来的问题构建一个最小的示例,以便其他人重现您的问题,帮助他们,帮助您!以下是本例中的一个最小示例:

    #include <iostream>
    
    class Base {
    public:
        virtual std::ostream& display(std::ostream& os) const =0;
    };
    
    class Derived1 : Base {
    public:
        std::ostream& display(std::ostream&) const
        {
            std::cout << "in Derived1.display" << std::endl;
        }
    };
    
    class Derived2 : Derived1 {
    public:
        void display(std::ostream&) const
        {
            std::cout << "in Derived2.display" << std::endl;
        }
    };
    
    int main()
    {
        Derived2 A;
        A.display(std::cout);
        return 0;
    }
    

    这会产生这个错误:

    main.cpp:18:10: error: virtual function 'display' has a different return type
          ('void') than the function it overrides (which has return type
          'std::ostream &' (aka 'basic_ostream<char> &'))
        void display(std::ostream&) const
        ~~~~ ^
    main.cpp:10:19: note: overridden virtual function is here
        std::ostream& display(std::ostream&) const
        ~~~~~~~~~~~~~ ^
    

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多