2016-04-06 39 views
0
ofstream& operator<<(ostream &outStream, const EventClass &eventObject) 
{ 
    outStream << eventObject.getEventName() << " event at " 
    << eventObject.getEventTime() << endl; 

    return(outStream); 
} 

我相信這段代碼足以分析錯誤。運算符<< overloading「錯誤:傳遞'const ....」

當我編譯我的代碼,我得到了以下錯誤:

error: passing ‘const EventClass’ as ‘this’ argument of ‘std::string EventClass::getEventName()’ discards qualifiers [-fpermissive]
outStream << eventObject.getEventName() << " event at "

error: passing ‘const EventClass’ as ‘this’ argument of ‘int EventClass::getEventTime()’ discards qualifiers [-fpermissive]
<< eventObject.getEventTime() << endl;

error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::ostream {aka std::basic_ostream}’
return(outStream);

任何想法如何解決這些錯誤?

+1

getEventName方法標記爲const嗎? –

+0

不,它不是。它是否必須是const來解決這個問題? – nm17

+0

是的,它必須是const來解決問題。 – kfsone

回答

0

eventObject是一個const對象的引用,因此其getEventName()getEventTime()方法需要被聲明爲const爲好,指定他們不會修改他們是所謂的對象,如:

std::string getEventName() const; 
int getEventName() const; 

此外,您的操作被聲明爲返回一個ofstream,但它需要返回一個ostream代替,以匹配輸入:

ostream& operator<<(ostream &outStream, const EventClass &eventObject) 
3

你需要ŧ o確保getEventNamegetEventTime被聲明爲const,如下:

std::string getEventName() const; 
int getEventTime() const; 
在聲明和實現的 EventClass

。這告訴編譯器這些方法不會以任何方式修改對象的字段。

此外,運營商的最後一行應該簡單地:return outStream;

編輯:也std::ofstream是不一樣的std::ostream。通常,對於operator<<,它需要被定義爲:

std::ostream& operator<<(std::ostream& os, const EventClass& eventObject) { 
    //blah 
} 

在涵蓋任何類型。

+1

你也應該指出'ostream'和'ofstream'是不一樣的,因爲最後一個錯誤。 –