operator << must take exactly one argument

前端 未结 4 2093
一个人的身影
一个人的身影 2020-12-04 12:06

a.h

#include \"logic.h\"
...

class A
{
friend ostream& operator<<(ostream&, A&);
...
};

logic.cpp

#inclu         


        
4条回答
  •  Happy的楠姐
    2020-12-04 12:27

    A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

     friend ostream& operator<<(ostream&, A&);
    

    then try to define it as a member function of the class logic

     ostream& logic::operator<<(ostream& os, A& a)
              ^^^^^^^
    

    Are you confused about whether logic is a class or a namespace?

    The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

    You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

    std::ostream& operator<<(std::ostream& os, const A& a)
    {
      return os << a.number;
    }
    

提交回复
热议问题