我正在编写一个类,我已经到了可以执行混合我的类类型对象和 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!\n\n");
cout << a + "World!\n\n";
//cout << "\n Good " + b; /* this is not possible because of the operands order */
}
如你所见,我可以这样做:
a + "W";
但不是,
"W" + a;
如代码最后一行所示。
我明白了原因。
第一个相当于:
a.operator+("W");
我的类(class)涵盖了这些内容。然而,第二个就像,
"W".operator(a);
未涵盖,文字本身不是我所理解的类的对象。因此,整个表达式不可能。
我知道我可以创建一个用户定义的文字,但这不是我想在这里做的。 (虽然我不确定它们是否会起作用)。
我在这个网站上找不到任何我应该相关的提示浏览问题,我在网上也找不到与我的问题相关的东西。
我的问题:
有没有一种方法可以使任一订单都有效?
最佳答案
这段代码:
cout << "\n Good " + b; /* this is not possible because of the operands order */
不起作用,因为您创建了 operator+
成员(而不是 const 成员)。如果您将其重写为独立函数(可能是 friend ),那么这个问题就会消失:
friend
CLS operator+(const CLS& lhs, const CLS& rhs)
{
CLS r;
r.str = lhs.str + rhs.str;
return r;
}
如果你创建额外的 ctor 来接受 const std::string &
它会更简单:
friend
CLS operator+(const CLS& lhs, const CLS& rhs)
{
return CLS( lhs.str + rhs.str );
}
请注意,您应该以这种方式重写现有的构造函数:
CLS(const char* param) : str( param )
{}
这是一种更清洁、更高效的方式
关于c++ - 重载运算符 : operand order when using C++ literals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553658/