2009-07-01 6 views
0

私は抽象クラスのヘッダファイルにこの機能が見つかりました:'仮想ostream&print(ostream&out)const;を実装する方法

virtual ostream & print(ostream & out) const; 

誰もこれがある機能の種類と派生クラスでそれを宣言する方法を教えてもらえますか? 私が知ることから、それは流出への参照を返すようです。

私はそれで何も私のccファイルでそれを実装する場合、私はコンパイラエラーを取得:

error: expected constructor, destructor, or type conversion before ‘&’ token

は、誰かが私にそれを使用する方法の簡単な実装を表示することができますか?

答えて

1

いくつかの実装:同じのostreamを返す

ostream& ClassA::print(ostream& out) const 
{ 
    out << myMember1 << myMember2; 
    return out; 
} 

a.print(myStream) << someOtherVariables; 

のような組み合わせは、しかし、まだそれをこのように使用する奇妙であることができます。

ostreamはstd名前空間の一部であり、参照しているクラスのグローバル名前空間または名前空間の一部ではありません。

1
#include <iostream> 
using namespace std; 

struct A { 
    virtual ostream & print(ostream & out) const { 
     return out << "A"; 
    } 
}; 

一般ストリーム出力のために使用< <操作者が(それがメンバ関数ではないので)そうすることができないので、印刷機能を仮想することが一般的です。

2

iostreamを含めるのを忘れていると、おそらくostreamが表示されます。また、C++標準ライブラリ名がネームスペースstd内にあるため、これをstd::ostreamに変更する必要があります。

Do not write using namespace std; in a header-file, ever!

必要に応じて実装ファイルに配置してもよいし、友人の例を書き留めてもかまいません。そのヘッダーを含むファイルはすべて標準ライブラリがグローバル名として表示されるため、大混乱で多くの匂いがします。他のグローバル名や他の名前との名前衝突の可能性が突然増加します。私は指示をまったく使わない(Herb SutterのUsing meを参照してください)。だから、この1

#include <iostream> 
// let ScaryDream be the interface 
class HereBeDragons : public ScaryDream { 
    ... 
    // mentioning virtual in the derived class again is not 
    // strictly necessary, but is a good thing to do (documentary) 
    virtual std::ostream & print(std::ostream & out) const; 
    ... 
}; 

へと実装ファイル(「.CPP」)わかりやすいクラス名のため

#include "HereBeDragons.h" 

// if you want, you could add "using namespace std;" here 
std::ostream & HereBeDragons::print(std::ostream & out) const { 
    return out << "flying animals" << std::endl; 
} 
+0

1にコードを変更:) – Eric

関連する問題