在 Linux 中编译时,“与 'std::operator<<' 中的'运算符<<'不

  • 本文关键字:operator Linux 中的 运算符 std 编译 c++
  • 更新时间 :
  • 英文 :


出于某种原因,我的代码在Visual Studio中工作,但在Linux编译器中不起作用,并且在Linux中给我一个错误,说

test_main.cpp:65: error: no match for 'operator<<' in 'std::operator<<'

[] 内有大量行,我的重载代码

String String::operator + (const String & s) const {
String temp;
temp.head = ListNode::concat(head,s.head);
return temp;
}

我的康卡特代码

String::ListNode * String::ListNode::concat(ListNode * L1, ListNode * L2)
{
return L1 == NULL ? copy(L2): new ListNode(L1->info, concat(L1->next, L2));
}

代码测试它

String firstString("First");
String secondString("Second");
cout << "+: " << firstString + secondString << endl;

声明

ostream & operator << (ostream & out, String & l);

身体

ostream & operator << (ostream & out, String & l)
{
l.print(out);
return out;
}

打印方式

void String::print(ostream & out)
{
    for (ListNode * p = head; p != nullptr; p = p->next)
        out << p->info;
}

在我的Visual Studio 2015环境中,这个打印FirstSecond并且不会像Linux那样给出错误,我不知道为什么

问题出在输出运算符上:

ostream & operator << (ostream & out, String & l);

操作的结果firstString + secondString是一个临时对象,非常量引用不能绑定到临时对象。

您需要更改函数以引用常量对象,例如

ostream & operator << (ostream & out, String const & l);
//                                           ^^^^^
//                              Note use of `const` here

最新更新