简体   繁体   中英

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

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) ;

A a;
B b;
a << b;

The compiler looks for the member operator<< in A here, ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM