rsk82
rsk82

Reputation: 29387

string operator overloading in c++ - I really don't get it

This is my code:

#include <iostream>
#include <string.h>
using namespace std;

string& operator+(string & lhs, int & rhs) {
    char temp[255];
    itoa(rhs,temp,10);
    return lhs += temp;
}

int main() {
  string text = "test ";
  string result = text + 10;
}

The result is:

test.cpp: In function 'int main()':
test.cpp:15:26: error: no match for 'operator+' in 'text + 10'
test.cpp:15:26: note: candidates are:
/.../

And should be test 10.

Upvotes: 0

Views: 117

Answers (2)

Mark B
Mark B

Reputation: 96241

You shouldn't take the int by reference. Just take it by value. Your problem is that you're trying to take a non-const reference to a literal integer - what would be the meaning of changing a literal?

That said you might consider against creating such an operator as it has a fair chance of confusing future maintainers.

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490128

An rvalue (10) can't bind to a non-const reference. You need to rewrite your operator+ to take either an int const & or just an int as its parameter.

While you're at it, you want to rewrite it so it doesn't modify the left operand either. An operator += should modify its left operand, but an operator + should not.

Upvotes: 14

Related Questions