C++ <&书信电报;重载运算符,为什么它可以';t仅返回类类型(无引用)
这是一个经典的cout重载friend成员函数。我这里有一个简单的问题。为什么必须返回到引用(ostream&)?。为什么不能回到奥斯特拉姆C++ <&书信电报;重载运算符,为什么它可以';t仅返回类类型(无引用),c++,C++,这是一个经典的cout重载friend成员函数。我这里有一个简单的问题。为什么必须返回到引用(ostream&)?。为什么不能回到奥斯特拉姆 class Time { private: int hours; int minutes; public: friend ostream& operator<<(std::ostream &os, const Time& t) { os<<t.hours<< "hours, " &
class Time {
private:
int hours;
int minutes;
public: friend ostream& operator<<(std::ostream &os, const Time& t) { os<<t.hours<< "hours, " <<t.minutes<< "minutes;
return os; //why it can't return to just ostream(witout reference &)
}
上课时间{
私人:
整小时;
整数分钟;
公众:friend ostream&operator应该是:
friend std::ostream &operator<<(std::ostream &os, const Time& t) {
os << t.hours << "hours, " << t.minutes << "minutes;
return os;
}
friend std::ostream&operatorostream
对象不可复制。因为它们代表“真实世界”的资源(控制台和文件等),所以复制它们没有任何意义
因此,由于它们不可复制,必须通过引用传递,因此运算符的正确返回类型您的示例代码无效(键入错误)。它应该通过引用返回std::ostream,而不是您的自定义类型。哦,糟糕,我会编辑它。我不明白,您正在尝试完成什么。您可能只使用ostream的内容。请记住,您应该能够多次使用重载运算符,如z=a请不要在收到ved答案。其中一个答案是指一个现在已不存在的问题。通常我会还原这些编辑,但由于您的问题显然不是关于返回时间
,我想这是可以的。至少您应该通知回答者,我已经这样做了,该问题已被编辑。也许可以删除“它必须重新运行ostream
对象…”然后答案再次同步