重载+运算符以添加const char

时间:2018-04-03 21:39:39

标签: c++ operator-keyword

我有一个结构:

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

当我写

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

it(ms visual 2015)说“没有操作符”+“匹配这些操作数”,鼠标在编辑器中的“+”源提示“操作数类型是const char [3] + text”,这表明我的重载运算符应该工作,不是吗? 我该怎么做才能将类型t字符串添加到const chars中呢?

2 个答案:

答案 0 :(得分:5)

仅当类位于运算符的 left 侧时,才会调用成员函数二元运算符重载。如果你需要处理你的班级在操作员右侧的情况,并且内置(不能识别如何使用你的班级),你需要一个非成员超载,例如(在课堂外定义):

// 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; }

这会使string x = "\r\n" + t;x设置为"\r\ntest"s

我强烈建议您现在阅读the operator overloading FAQ,然后再将自己写入角落;您学习的第一件事就是不要将operator+实现为成员函数(只有+=才会成员)。

答案 1 :(得分:4)

我假设您打算使用

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

而不是

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

当您将operator+定义为成员函数时,第一个参数必须是该类的对象。

您需要使用:

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

如果您想使用

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

你需要一个支持第二种形式的非成员函数。

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

要对称,您应该支持它们作为非成员函数。

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

并在另一方面实施一个。

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

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