【发布时间】:2016-02-19 23:06:51
【问题描述】:
编辑:
在一些 cmets 之后,这是我现在的代码,遵循 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);
我的调用:(设备是Node类型,val返回设备)
cout << device->val << endl;
我的错误:
错误 LNK2019 未解析的外部符号 “类 std::basic_ostream > std::char_traits > & __cdecl 运算符 &,类设备 常量 &)" (??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;
}
但是当尝试使用这个重载时——(设备是设备类型)
cout << device << endl;
它标记为已读并说-
错误 C2679 二进制 '
为什么会出现此错误,我该如何解决?我在网上看了,但找不到在类内有效的方法,只有这个:
friend ostream& 运算符
这对我也不起作用。
【问题讨论】:
-
“这对我也不起作用” 它为什么对你不起作用?您需要像这样重载全局运算符:
ostream& operator(ostream& out, const Device& dev). -
好的,没有“
-
抱歉,打错了:
ostream& operator<<(ostream& out, const Device& dev),是的,在课堂之外。 -
我得到了完全相同的错误。
ostream& operator<<(ostream& out, const Device& v) { out << "Device " << v.get_name() << " Has an ID of: " << v.get_id(); return out; }
标签: c++ operator-overloading operators iostream