Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"no match for 'operator<<' in 'std::operator<<'" error when compiling in Linux, VS doesn't present this error

Tags:

c++

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

like image 461
Alex Chapp Avatar asked Apr 21 '26 11:04

Alex Chapp


1 Answers

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, e.g.

ostream & operator << (ostream & out, String const & l);
//                                           ^^^^^
//                              Note use of `const` here
like image 155
Some programmer dude Avatar answered Apr 23 '26 02:04

Some programmer dude