2015-08-26 66 views
2

我想超載std::ostream& operator<<這樣做:重載運營商的std :: ostream的和運營商<<打印實例內存地址

#include <iostream> 

class MyTime 
{ 
private: 
    unsigned char _hour; 
    unsigned char _minute; 
    float _second; 
    signed char _timeZone; 
    unsigned char _daylightSavings; 
    double _decimalHour; 

    friend std::ostream& operator<<(std::ostream&, const MyTime&); 
public: 
    MyTime(); 
    ~MyTime(); 
}; 

和操作執行:

std::ostream& operator<<(std::ostream &strm, const MyTime &time) 
{ 
    return strm << (int)time._hour << ":" << (int)time._minute << ":" << time._second << " +" << (int)time._daylightSavings << " zone: " << (int)time._timeZone << " decimal hour: " << time._decimalHour; 
} 

但是,當我這樣做:

MyTime* anotherTime = new MyTime(6, 31, 27, 0, 0); 
std::cout << "Time: " << anotherTime << std::endl; 

它只打印anotherTime內存地址。

我在做什麼錯?

回答

6

您的意思是:

std::cout << "Time: " << *anotherTime << std::endl; 

,或者甚至更好:

MyTime anotherTime (6, 31, 27, 0, 0); 
std::cout << "Time: " << anotherTime << std::endl; 
+0

或者可能'指明MyTime對應anotherTime(6,31,27,0,0);' – juanchopanza

+0

@juanchopanza是的,絕對。 –

+0

是的,你是對的。我剛開始學習C++。謝謝。 – VansFannel

2

你的運營商期望通過const引用一個實例對象,但你給它一個指針。要麼是std::cout << "Time: " << *anotherTime << std::endl;(注意*)或添加其他運營商:

friend std::ostream& operator<<(std::ostream&, const MyTime*);

1
std::cout << "Time: " << anotherTime << std::endl; 
以上anotherTime實例代碼

是指明MyTime對應*,但必須指明MyTime對應。

你有兩個解決方案來解決這個問題:

製作堆棧指明MyTime對應,並且它會正常工作,因爲現在anotherTime不是指針。

MyTime anotherTime(6, 31, 27, 0, 0); 
    std::cout << "Time: " << anotherTime << std::endl; 

間接引用代碼中的指針,就像這樣:

MyTime* anotherTime = new MyTime(6, 31, 27, 0, 0); 
std::cout << "Time: " << *anotherTime << std::endl;