2016-09-03 3 views
2
//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を使用する必要があります。それは私の研究室の指示にあり、変更できないからです。 私は、derived2の表示関数でDerived1の表示関数を呼び出す必要があります。これは簡単でわかります。したがって、この同じ名前で異なる戻り値の型を持つ派生クラスの新しい関数を作成する

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

ようですがDerived2に誤りがあるこの

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

のようなメインに呼び出される「戻り値の型は同一ではないにも戻り値の型との共変 『のstd :: ostreamに&』の関数のシグネチャ(この場合は戻り値の型)がオーバーライドされている関数と一致する必要がありますが、私の研究室では、それを上書きしない新しい関数を作成したいと思うと思います、しかし同じ名前で?私はDerived2のdisplay()のDerived1からdisplay()を呼び出さなければならないからです。何かご意見は?

私はdisplay()で何をしようとしていますが、オーバーライドされていると見なされます。

答えて

3

戻りタイプがではありません。共変量

"ラボ"の要求を忘れたと思います。あまりにもこれらを読む:

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

は...途中でのStackOverflowへようこそ!他の人があなたを再現するために、最小限の例を構築するためにあなたの将来の質問のために確認してください問題を解決し、助けてください!ここで、この場合の最小の例の一例である。

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 
    ~~~~~~~~~~~~~^
:このエラーを生じる
#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; 
} 

関連する問題