c++operator-overloadingoperatorsiostream

C++ ostream overloading is not working, what am I doing wrong?


Edit:

After some comments, this is my code now, following THIS link.(Better, but I still have an error)

Out of everything:

ostream& operator<<(ostream& out, Device& v) {
    out << "Device " << v.get_name() << " Has an ID of: " << v.get_id();
    return out;
}

Inside Device class:

friend ostream& operator<<(ostream& os, const Device& v);

My call: (device is of type Node<Device>, and val returns the device)

cout << device->val << endl;

My error:

Error LNK2019 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits > std::char_traits > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits > &,class Device const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABVDevice@@@Z) referenced in function "void __cdecl print_devices(class Node *)" (?print_devices@@YAXPAV?$Node@VDevice@@@@@Z)

Original:

I was taught that overloading an operator is done like this:

ostream& Device::operator<<(ostream &out) {
    out << "Device " << this->name << " Has an ID of: " << this->id;
    return out;
}

But when trying to use this overloading - (device is type Device)

cout << device << endl;

It marks in red and says -

Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'Device' (or there is no acceptable conversion)

Why do I get this error, and how can I fix it? I looked online, but could not find a method that works inside the class, only this:

friend ostream& operator<< (ostream &out, Point &cPoint);

Which did not work for me either.


Solution

  • What you have declared inside your Device class is

    friend ostream& operator<<(ostream& os, const Device& v);
    

    but what you have provided the implementation for is

    ostream& operator<<(ostream& out, Device& v) {
        out << "Device " << v.get_name() << " Has an ID of: " << v.get_id();
        return out;
    }
    

    which is not the same thing! You told the compiler there is a friend function which takes a reference to an ostream and a const reference to a Device - but the function you have provided misses the const in front of Device.