gpt4 book ai didi

C++ ostream 重载不起作用

转载 作者:太空狗 更新时间:2023-10-29 21:39:05 26 4
gpt4 key购买 nike

编辑:

经过一些评论,这是我现在的代码,在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类型,val返回device)

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)

为什么会出现此错误,我该如何解决?我在网上看了看,但找不到在类里面有效的方法,只有这个:

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

这对我也不起作用。

最佳答案

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

关于C++ ostream 重载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com