Function must have exactly one argument

前端 未结 2 1558
萌比男神i
萌比男神i 2021-01-21 15:48

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

I\'m geting the error:

TOutputFile& TOutputFile::operator<<(TOutpu         


        
相关标签:
2条回答
  • 2021-01-21 16:23

    Operator overloaded functions which are defined as member functions accept only one parameter. In case of overloading << operator, more than one parameter is required. Making it a friend function solves this issue.

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

    A function marked as friend will allow that function to access private member of the class to which it is a friend.

    0 讨论(0)
  • 2021-01-21 16:42

    Check the 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.

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

    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 <<
    }
    
    0 讨论(0)
提交回复
热议问题