重载运算符:使用C++文本时的操作数顺序

Overloading operators: operand order when using C++ literals

本文关键字:操作数 顺序 文本 C++ 运算符 使用 重载      更新时间:2023-10-16

我正在编写一个类,我可以执行混合类类型对象和C++文字的操作,但仅限于一个方向。

下面是一个简化的代码,显示了这个想法:

#include <iostream>
#include <string>
using namespace std;
class CLS
{
string str;
public:
CLS(const char* param)
{    str = param;   }
CLS operator+(const CLS& rhs)
{
str = str + rhs.str;
return *this; }
friend ostream& operator<<(ostream& out, const CLS& rhs);
};
ostream& operator<<(ostream& out, const CLS& rhs)
{
out << rhs.str;
return out; }
int main()
{
CLS a("n Hello ");
CLS b("bye!nn");
cout << a + "World!nn";
//cout << "n Good " + b; /* this is not possible because of the operands order */
}

如您所见,我可以执行以下操作:

a + "W";

但不是,

"W" + a;

如代码的最后一行所示。

我明白原因。

第一个相当于:

a.operator+("W");

我的课程涵盖了这一点。然而,第二个就像,

"W".operator(a);

它没有被涵盖,文字本身不是我理解的类的对象。因此,整个表达不可能。

我知道我可以创建一个用户定义的文字,但这不是我在这里想做的。(虽然我不确定他们是否会工作)。

我在这个网站上找不到任何我应该相关的提示浏览问题,我无法在网上获得与我的问题相关的内容。

我的问题:

有没有办法使任一订单起作用?

此代码:

cout << "n Good " + b; /* this is not possible because of the operands order */

不起作用,因为您创建了operator+成员(而不是常量成员)。如果您将其重写为独立函数(可能是朋友),那么这个问题就会消失:

friend 
CLS operator+(const CLS& lhs, const CLS& rhs)
{
CLS r;
r.str = lhs.str + rhs.str;
return r; 
}

如果您创建接受const std::string &的其他 CTOR,它会更简单:

friend 
CLS operator+(const CLS& lhs, const CLS& rhs)
{
return CLS( lhs.str + rhs.str );
}

请注意,您应该以这种方式重写现有构造函数:

CLS(const char* param) : str( param )
{}

这是更清洁,更高效的方式

您可以添加全局函数:

inline CLS operator+(const char *lhs, const CLS& rhs)
{
return CLS(lhs) + rhs;
}