Home > other >  Overloading << operator for my own class why is this not working?
Overloading << operator for my own class why is this not working?

Time:11-28

I have a class and I wanna overload the << operator in it:

class Vector3
{
    int x;
    int y;
    int z;
public:
    Vector3(int a, int b, int c) : x{a}, y{b}, z{c} {}
    Vector3 operator (const Vector3& v);
    friend std::ostream& operator<<(std::ostream& ost, const Vector3& v);
    



};

But basically I want to be able to access the data members so here I did it with a friend function and just defined the function in a different file:

std::ostream& operator<<(std::ostream& ost, const Vector3& v)
{
    return ost << '(' << v.x << ',' << v.y << ',' << v.z << ')';
}

But my question is how come when I don't use a friend function and just declare the function like this:

std::ostream& operator<<(std::ostream& ost);

Then define it in a different file:

std::ostream& Vector3::operator<<(std::ostream& ost)
{
   return ost << '(' << x << ',' << y << ',' << z << ')';
}

When I try to actually use it

int main()
{
   Vector3 u(2,4,3);
   std::cout << u;

}

It just says:

> no operator matches these operands            operand types are:
> std::ostream << Vector3

But if I do u.operator<<(std::cout); Then it works? But why? I thought that std::cout << u; is basically the same as u.operator<<(std::cout);

CodePudding user response:

A a;
B b;
a << b;

The compiler looks for the member operator<< in A here, i.e. if A::operator(B const&) exists, the code snipped above uses it, but B::operator<<(A&) is not considered.

For your code this means the member operator required is std::ostream::operator<<(Vector3 const&) which you cannot add, since std::ostream is defined in the standard library. Your only choice here is a free function.

CodePudding user response:

Order matters. The overload you provided defines u << cout and not cout << u.

  •  Tags:  
  • c
  • Related