std :: ostream需要函数帮助

时间:2011-01-26 03:31:24

标签: c++

我需要有人一个接一个地向我解释这些代码行,我需要帮助使用“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;
}

更新1:当我使用此功能时,它不会编译,错误说:

的std :: ostream的&安培; class :: operator&lt;&lt;(std :: ostream&amp; os,const Telegram&amp; t)必须只有一个参数

2 个答案:

答案 0 :(得分:7)

这些行只是添加了将Telegram对象处理为标准输出流类的功能。

当您添加新类并希望输出流(如cout)智能地处理它们时,您需要添加一个新的<<运算符方法,该方法将新对象类型作为第二个参数。< / p>

上面的代码正是这样做的。稍后执行语句时:

Telegram tg("Bob", "Hello, how are you?");
cout << tg;

您的问题中的函数将以流作为第一个参数并将您的tg对象作为第二个参数进行调用,然后它将能够以适合该类的格式输出数据。

这实际上是我无法理解的早期C ++内容之一。尽管该类应该是自包含的,但实际上是在向不同的类添加一些东西来处理输出。一旦你理解了为什么会发生这种情况(因为它是负责输出事物而不是你自己的类的ostream类),它有希望有意义。


希望通过一个更简单的例子让它更清晰:

1    inline std::ostream& operator<<(std::ostream& os, const Telegram& t) {
2      os << "message: " << t.Msg;
3      return os;
4    }

第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;
}

输出:

7
int: 7

第一个是通过调用getter函数来检索整数,第二个是调用我们添加到<<的{​​{1}}运算符函数。

答案 1 :(得分:2)

相关问题