【问题标题】:Function must have exactly one argument函数必须只有一个参数
【发布时间】:2019-05-21 11:35:30
【问题描述】:

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


};

那个运算符重载有什么问题?

【问题讨论】:

  • 函数原型应该在类声明/定义之后。
  • 您对operator&lt;&lt;() 的定义在类内部,这意味着它是成员。因此,除了您指定的参数之外,它还有一个隐含的this 参数。将定义移到类之外。 (然后你会看到其他问题,但你还没有问过这些问题)。
  • 将其设为友元函数将解决问题,因为届时它将不再是成员函数。

标签: c++ function


【解决方案1】:

查看reference

operator&gt;&gt;operator&lt;&lt; 的重载采用 std::istream&amp;std::ostream&amp; 作为左侧参数被称为插入和 提取运算符。由于他们将用户定义的类型作为 正确的参数(a@b 中的 b),它们必须作为非成员实现

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

如果您正在开发自己的流类,您可以使用单个参数重载operator&lt;&lt;作为成员函数。在这种情况下,实现看起来像这样:

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

【讨论】:

    【解决方案2】:

    定义为成员函数的运算符重载函数只接受一个参数。在重载&lt;&lt; 运算符的情况下,需要多个参数。将其设为friend 函数可解决此问题。

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

    标记为friend 的函数将允许该函数访问它是朋友的类的私有成员。

    【讨论】:

    • 请显示成员变体。也可以使用const T&amp; a
    • 我不确定成员变体在这里意味着什么。
    • 只是另一种解决方案,OP 得到的错误消息是直接指导。
    猜你喜欢
    • 2017-02-05
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2021-10-23
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多