如何ostream&引用自动创建?

时间:2017-05-26 18:05:21

标签: c++

在使用它的类中的重载!函数中,它将在main()函数中使用,如

operator<<()

&lt;&lt;&lt;&lt;&lt;&lt;操作员能够创建ostream&amp;参考 我们可以这样做吗

int main()
{
  MyOwnClass myClass;
  cout << myClass;

}

因为它是朋友的功能

1 个答案:

答案 0 :(得分:1)

您必须重载输出流运算符 std::ostream& << myclass。二进制运算符(例如<<)既可以实现为其第一个操作数类型的成员(并将第二个操作数作为唯一参数),也可以作为独立函数将两个操作数作为参数实现。

此处,只有第二个选项是可能的,因为您无法更改std::ostream的定义。例如

struct myclass // just an example
{
  int data;
};

std::ostream& operator<<(std::ostream&os, myclass const&obj)
{
  return os << obj.data;
}

在函数体内,调用operator<<(std::ostream&, int)iostreamostream中定义,并返回对输入时收到的std::ostream& operator<<(std::ostream&os, myclass const&obj) { for(auto x:obj.table) os << std::setprecision(12) << x return os; } 的引用。如果是更复杂的类,您只需返回流即可。

Select