2009-07-01 52 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& ClassA::print(ostream& out) const 
{ 
    out << myMember1 << myMember2; 
    return out; 
} 

返回相同的ostream讓像

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可見。您還需要將其更改爲std::ostream,因爲C++標準庫名稱位於命名空間std內。

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

這是確定將它放入實現文件,如果你想,或者,如果你寫了一個朋友的例子。因爲包含該頭文件的任何文件都會將所有標準庫看作全局名稱,這是一個巨大的混亂並且聞起來很多。它突然增加了與其他全球名稱或其他using'編號名稱發生名稱衝突的機會 - 我將完全避免使用指令(請參閱Herb Sutter的Using me)。因此,更改代碼到這個

#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 2009-07-01 15:34:18