c++ - 函数必须只有一个参数

标签 c++ function

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

我收到错误:

TOutputFile& TOutputFile::operator<<(TOutputFile&, T)' must have exactly one argument

在以下代码上:

template<class T>
TOutputFile &operator<<(TOutputFile &OutFile, T& a);

class TOutputFile : public Tiofile{
public:
   TOutputFile (std::string AFileName);
   ~TOutputFile (void) {delete FFileID;}

   //close file
   void close (void) {
    if (isopened()) {
         FFileID->close();
         Tiofile::close();
      }
   }
   //open file
   void open  (void) {
      if (!isopened()) {
         FFileID->open(FFileName, std::ios::out);
         Tiofile::open();
      }
   }

   template<class T>
   TOutputFile &operator<<(TOutputFile &OutFile, const T a){
    *OutFile.FFileID<<a;
    return OutFile;
   }

protected:
   void writevalues  (Array<TSequence*> &Flds);
private:
   std::ofstream * FFileID;         


};

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

最佳答案

检查reference

The overloads of operator>> and operator<< that take a std::istream& or std::ostream& as the left hand argument are known as insertion and extraction operators. Since they take the user-defined type as the right argument (b in a@b), they must be implemented as 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 <<
}

关于c++ - 函数必须只有一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237411/

相关文章:

c++ - LPTSTR 到 int (c++)

c - 传递结构与单个结构元素

c++ - 如何修复二维嵌套 vector 的分割错误

javascript - JS中return语句中的问号是什么意思?

c++ - 如何保持循环直到密码满足 C++ 中的条件?

javascript 函数未被调用/无法从 html 表单工作

function - 该函数如何返回其值?

C++ 模板完整指南。赋值运算符

c++ - g++ 空函数删除是否递归工作?

c++函数将额外的空条目保存到文件中