For some reason my code works in Visual Studio but not in the Linux compiler and gives me an error in Linux saying
test_main.cpp:65: error: no match for 'operator<<' in 'std::operator<<'
With tons of lines inside of [] my overloading code
String String::operator + (const String & s) const {
String temp;
temp.head = ListNode::concat(head,s.head);
return temp;
}
my concat code
String::ListNode * String::ListNode::concat(ListNode * L1, ListNode * L2)
{
return L1 == NULL ? copy(L2): new ListNode(L1->info, concat(L1->next, L2));
}
code testing it
String firstString("First");
String secondString("Second");
cout << "+: " << firstString + secondString << endl;
declaration
ostream & operator << (ostream & out, String & l);
Body
ostream & operator << (ostream & out, String & l)
{
l.print(out);
return out;
}
Print method
void String::print(ostream & out)
{
for (ListNode * p = head; p != nullptr; p = p->next)
out << p->info;
}
In my Visual Studio 2015 environment this print FirstSecond
and doesn't give an error like in Linux and I have no idea why
The problem is with the output operator:
ostream & operator << (ostream & out, String & l);
The result of the operation firstString + secondString
is a temporary object, and non-constant references can't bind to temporary object.
You need to change your function to take a reference to a constant object, eg
ostream & operator << (ostream & out, String const & l);
// ^^^^^
// Note use of `const` here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.