函数必须只有一个参数

use*_*073 2 c++ function

我已经很长时间没有用C ++编写代码了,我正在尝试修复一些旧代码。

我收到错误消息:

TOutputFile& TOutputFile::operator<<(TOutputFile&, T)' must have exactly one argument
Run Code Online (Sandbox Code Playgroud)

在以下代码上:

TOutputFile& TOutputFile::operator<<(TOutputFile&, T)' must have exactly one argument
Run Code Online (Sandbox Code Playgroud)

该运算符重载有什么问题?

Ayx*_*xan 5

检查参考

的重载operator>>operator<<称取一std::istream&std::ostream&作为左手参数被称为插入和提取运算符。由于它们将用户定义的类型作为正确的参数(a @ b中的b),因此必须将其实现为non-members

因此,它们必须是非成员函数,并且在它们打算成为流运算符时正好采用两个参数。

如果要开发自己的流类,则可以operator<<将单个参数作为成员函数进行重载。在这种情况下,实现将如下所示:

template<class T>
TOutputFile &operator<<(const T& a) {
  // do what needs to be done
  return *this; // note that `*this` is the TOutputFile object as the lefthand side of <<
}
Run Code Online (Sandbox Code Playgroud)