函数必须只有一个参数 [英] Function must have exactly one argument

查看:245
本文介绍了函数必须只有一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've not coded in C++ for a long time and I'm trying to fix some old code.

我遇到了错误:

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;         


};

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

What's is wrong with that operator overloading ?

推荐答案

检查参考

operator>> operator<< 的重载需要 std :: istream& std :: ostream& 作为左手参数称为插入和提取运算符.由于它们采用用户定义的类型作为正确的参数(a @ b中的b),必须将其实现为非成员.

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.

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

Hence, they must be non-member functions, and take exactly two arguments when they are meant to be stream operators.

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

If you are developing your own stream class, you can overload operator<< with a single argument as a member function. In this case, the implementation would look something like this:

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

这篇关于函数必须只有一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆