2012-02-10 13 views
1

Iはオーバーロード<<オペレータが宣言したそれぞれが種々のコンピュータ構成要素を表すクラスの数を有しますそのコンポーネントは、他のコンポーネントで構成されています。ユニークなIDだけでなく、すべてのコンポーネントが公に派生する他の関数を生成するために、Componentという基本クラスを作成することにしました。もちろん、オーバーロードされた<<演算子は、Componentオブジェクトへのポインタでは動作しません。オーバーロード出力オペレータは

私はので、私のようなものを行うことができ、各派生クラスの <<オペレータによって上書きされる純粋仮想関数のようなものをもたらすのだろうかと思いまして

overloading << operators and inherited classes

答えて

5

:またに関連

Component* mobo = new MotherBoard(); 

cout << *mobo << endl; 

delete mobo; 

をたぶんこのようなもの:

#include <iostream> 

class Component 
{ 
public: 
    // Constructor, destructor and other stuff 

    virtual std::ostream &output(std::ostream &os) const 
     { os << "Generic component\n"; return os; } 
}; 

class MotherBoard : public Component 
{ 
public: 
    // Constructor, destructor and other stuff 

    virtual std::ostream &output(std::ostream &os) const 
     { os << "Motherboard\n"; return os; } 
}; 

std::ostream &operator<<(std::ostream &os, const Component &component) 
{ 
    return component.output(os); 
} 

int main() 
{ 
    MotherBoard mb; 
    Component &component = mb; 

    std::cout << component; 
} 
+0

+1私は実際にこれを数回見ましたが、意味があります。しかし、 'output'がpublicであるとすれば、' operator << 'は友人である必要はありません。また、以前は、 'virtual std :: ostream&print(std :: ostream&out)const; 'というシグネチャを手動で呼び出すとチェーンされるように見えました:' myobj.output(std :: cout)<

+0

@DavidRodríguez-dribeasあなたが正しいです、友人宣言は必要ではありません、私は推測する習慣の力だけです。 :)あなたの提案に従ってコードを更新しました。 –

関連する問題