重载运算符std :: ostream&运营商LT;<打印实例内存地址

时间:2015-08-26 18:01:29

标签: c++

我试图超载std::ostream& operator<<这样做:

#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内存地址。

我做错了什么?

3 个答案:

答案 0 :(得分:6)

你的意思是:

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

或者,甚至更好:

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

答案 1 :(得分:2)

您的运算符需要const引用的实例对象,但是您给它一个指针。可以std::cout << "Time: " << *anotherTime << std::endl;(注意*)或添加其他运算符:

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

答案 2 :(得分:1)

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

在另一个时间实例上面的代码是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;