我需要有人一个一个地向我解释这些代码行,我需要帮助使用"ostream"和简单的例子.谢谢 :).
inline std::ostream& operator<<(std::ostream& os, const Telegram& t)
{
os << "time: " << t.DispatchTime << " Sender: " << t.Sender
<< " Receiver: " << t.Receiver << " Msg: " << t.Msg;
return os;
}
Run Code Online (Sandbox Code Playgroud)
更新1:当我使用此功能时,它不会编译,错误说:
std :: ostream&class :: operator <<(std :: ostream&os,const Telegram&t)必须只有一个参数
这些行只是添加了将Telegram对象处理为标准输出流类的功能.
当您添加新类并希望输出流像cout智能处理它们时,您需要添加一个新的<<运算符方法,该方法将新对象类型作为第二个参数.
上面的代码正是这样做的.稍后执行语句时:
Telegram tg("Bob", "Hello, how are you?");
cout << tg;
Run Code Online (Sandbox Code Playgroud)
您的问题中的函数将被调用,流作为第一个参数,您的tg对象作为第二个参数,然后它将能够以适合该类的格式输出数据.
这实际上是我无法理解的早期C++事情之一.尽管该类应该是自包含的,但实际上是在向不同的类添加一些东西来处理输出.一旦你理解了为什么会发生这种情况(因为它ostream是负责输出事物而不是你自己的类的类),它将有希望有意义.
希望通过一个更简单的例子使其更清晰:
1 inline std::ostream& operator<<(std::ostream& os, const Telegram& t) {
2 os << "message: " << t.Msg;
3 return os;
4 }
Run Code Online (Sandbox Code Playgroud)
第1行只是函数定义.它允许您返回流本身(您传入),以便您可以链接<<段.这operator<<只是您提供的函数,即<< tg放入输出流语句时调用的函数.
第2行使用<<已经定义的更基本的语句(在这种情况下,Msg是什么类型,可能是一个字符串).
然后第3行返回流,再次允许链接<<段.
基本思想是为构成您的类型的数据类型提供operator<<基于现有operator<<函数的函数.
并使用一个简单的包装类,其中只包含int:
#include <iostream>
// This is my simple class.
class intWrapper {
public:
intWrapper (int x) { myInt = x; };
int getInt (void) { return myInt; }
private:
int myInt;
// Must be friend to access private members.
friend std::ostream& operator<< (std::ostream&, const intWrapper&);
};
// The actual output function.
inline std::ostream& operator<< (std::ostream& os, const intWrapper& t) {
os << "int: " << t.myInt;
return os;
}
// Main program for testing.
// Output with getter and with ostream.
int main (void) {
class intWrapper x(7);
std::cout << x.getInt() << std::endl; // ostream already knows about int.
std::cout << x << std::endl; // And also intWrapper, due to the
// function declared above.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
7
int: 7
Run Code Online (Sandbox Code Playgroud)
第一个是通过调用getter函数来检索整数,第二个是通过调用<<我们添加的运算符函数ostream.