C++ ostream 重载不起作用

C++ ostream overloading not working

编辑:

经过一些评论,这是我现在的代码,遵循THIS link。(更好,但我仍然有错误)

万事俱备:

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

设备内部 class:

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

我的电话:(设备是节点类型,并且 val returns 设备)

cout << device->val << endl;

我的错误:

Error LNK2019 unresolved external symbol "class std::basic_ostream > std::char_traits > & __cdecl operator<<(class std::basic_ostream > &,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)

原文:

有人教我重载运算符是这样的:

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

但是当尝试使用此重载时 - (设备类型为 Device)

cout << device << endl;

它标记为已读并说 -

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

为什么会出现此错误,我该如何解决?我上网查了一下,没找到在class里面有效的方法,只有这个:

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

这对我也不起作用。

Overloading C++ STL methods

我不相信您可以根据此答案在 STL 流上重载 << 运算符。

您发布的错误是关于编译器未找到函数实现的。

#include <iostream>

struct MyType
{
    int data{1};

};

std::ostream& operator<< (std::ostream& out, const MyType& t)
{
    out << t.data;
    return out;
}

int main()
{
    MyType t;

    std::cout << t << std::endl;

    return 0;
}

您在 Device class 中声明的是

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

但是您提供的实现是

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

不是一回事!你告诉编译器有一个 friend 函数引用了一个 ostream 和一个 const 引用了一个 Device - 但是这个函数你已提供 Device.

前的 const 遗漏