首页 > 解决方案 > 函数必须只有一个参数

问题描述

我很久没有用 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;         


};

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

标签: c++function

解决方案


检查参考

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

因此,它们必须是非成员函数,并且当它们是流操作符时,它们恰好需要两个参数。

如果您正在开发自己的流类,则可以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 <<
}

推荐阅读