【问题标题】:C++ ostream overloading not workingC ++ ostream重载不起作用
【发布时间】: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&amp; operator(ostream&amp; out, const Device&amp; dev).
  • 好的,没有“
  • 抱歉,打错了:ostream&amp; operator&lt;&lt;(ostream&amp; out, const Device&amp; dev),是的,在课堂之外。
  • 我得到了完全相同的错误。 ostream&amp; operator&lt;&lt;(ostream&amp; out, const Device&amp; v) { out &lt;&lt; "Device " &lt;&lt; v.get_name() &lt;&lt; " Has an ID of: " &lt;&lt; v.get_id(); return out; }
  • 看看msdn.microsoft.com/en-us/library/1z2f6c2k.aspx“为你自己的类重载

标签: c++ operator-overloading operators iostream


【解决方案1】:

你在 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 - 但是您提供的函数错过了前面的 const Device.

【讨论】:

  • 天哪,我没注意到!我将其全部更改为 const,但随后出现了数十个错误,因此我使用了非常量值 - Device& v。非常感谢!
【解决方案2】:

Overloading C++ STL methods

我不相信您可以根据这个答案在 STL 流上重载

【讨论】:

【解决方案3】:

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

#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;
}

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多