简体   繁体   中英

overloading + operator to add a const char

I have a struct :

struct t { 
 string data;
 t(string new_data) { data = new_data; }
 string operator +(const char *operand) { return data + string(operand); }
}

when I write

t y="text"; 
string x = "\r\n" + t;

it (ms visual 2015) says "no operator "+" matches these operands" and the mouse over hint of the "+" source in the editor says "operand types are const char [3] + text" which suggest my overloaded operator should work, doesn't it? What do I have to do so that I can add type t strings to const chars like that?

Member function binary operator overloads are only invoked when the class is on the left side of the operator. If you need to handle the case where your class is on the right hand side of the operator with a built-in (that doesn't recognize how to work with your class) on the left, you need a non-member overload, eg (defined outside the class):

// No need to explicitly stringify operand, since string already overloads
// + for const char*
string operator+(const char *left, const t& right) { return left + right.data; }

Which would make string x = "\\r\\n" + t; set x to "\\r\\ntest"s .

I'd strongly recommend reading the operator overloading FAQ now, before you write yourself into a corner here; one of the first things you learn is not to implement operator+ as a member function (only += would be a member).

I am assuming that you meant to use

string x = "\r\n" + y; // y is the object, t is the type.

and not

string x = "\r\n" + t;

When you define operator+ as a member function, the first argument has to be an object of the class.

You need to use:

string x = y + "\r\n";

If you want to be able use

string x1 = y + "\r\n";
string x2 = "\r\n" + y;

you need a non-member function that supports the second form.

string operator+(const char* operand, t const& y);

To be symmetric, you should support both of them as non-member functions.

string operator+(t const& y, const char* operand);
string operator+(const char* operand, t const& y);

and implement one in terms of the other.

string operator+(t const& y, const char* operand)
{
   return (y.data + string(operand));
}

string operator+(const char* operand, t const& y)
{
   return (y + operand);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM