[英]Overloaded operator std::ostream& operator<< prints instance memory address
I'm trying to overload std::ostream& operator<<
doing this: 我正在尝试重载
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();
};
And operator's implementation: 和运营商的实施:
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;
}
But when I do this: 但是当我这样做时:
MyTime* anotherTime = new MyTime(6, 31, 27, 0, 0);
std::cout << "Time: " << anotherTime << std::endl;
It only prints anotherTime
memory address. 它只打印
anotherTime
内存地址。
What am I doing wrong? 我究竟做错了什么?
You meant: 你的意思是:
std::cout << "Time: " << *anotherTime << std::endl;
Or, even better: 或者,甚至更好:
MyTime anotherTime (6, 31, 27, 0, 0);
std::cout << "Time: " << anotherTime << std::endl;
Your operator expects an instance object by const reference but you're giving it a pointer. 您的操作符需要const引用的实例对象,但是您给它一个指针。 Either do
std::cout << "Time: " << *anotherTime << std::endl;
要么做
std::cout << "Time: " << *anotherTime << std::endl;
(note the *
) or add another operator: (注意
*
)或添加另一个运算符:
friend std::ostream& operator<<(std::ostream&, const MyTime*);
std::cout << "Time: " << anotherTime << std::endl;
in that code above anotherTime instance is a myTime*, but it must be myTime. 在上面的代码中,anotherTime实例是myTime *,但它必须是myTime。
You have two solutions to fix this: 你有两个解决方案来解决这个问题:
Making myTime on stack, and it will work fine because anotherTime now not a pointer. 在堆栈上制作myTime,它会正常工作,因为anotherTime现在不是指针。
MyTime anotherTime(6, 31, 27, 0, 0);
std::cout << "Time: " << anotherTime << std::endl;
dereference the pointer in your code, like this: 取消引用代码中的指针,如下所示:
MyTime* anotherTime = new MyTime(6, 31, 27, 0, 0);
std::cout << "Time: " << *anotherTime << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.