繁体   English   中英

重载运算符std :: ostream&operator <<打印实例内存地址

[英]Overloaded operator std::ostream& operator<< prints instance memory address

我正在尝试重载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内存地址。

我究竟做错了什么?

你的意思是:

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

或者,甚至更好:

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

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

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM