C++ ostream 重载不起作用,我做错了什么?

问题描述 投票:0回答:3

编辑:

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

一切皆出自:

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

设备类内部:

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

我的呼叫:(

device
的类型为
Node<Device>
,并且
val
返回设备)

cout << device->val << endl;

我的错误:

错误 LNK2019 无法解析的外部符号 “类 std::basic_ostream std::char_traits > & __cdecl 运算符<<(class std::basic_ostream &,class Device 常量&)” (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABVDevice@@@Z) 在函数“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;

它用红色标记并写着 -

错误 C2679 二进制 '<<': no operator found which takes a right-hand operand of type 'Device' (or there is no acceptable conversion)

为什么会出现此错误,如何修复它?我在网上查了一下,但找不到在类中有效的方法,只有这个:

ostream&运营商朋友<< (ostream &out, Point &cPoint);

这对我来说也不起作用。

c++ operator-overloading operators iostream
3个回答
2
投票

您在

Device
类中声明的是

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
的引用和对 Device
const
引用 - 但您提供的函数缺少
const
前面的
Device


0
投票

重载 C++ STL 方法

我不相信你可以超载<< operator on an STL stream based on this answer.


0
投票

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

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.