重载运算符:使用 C++ 文字时的操作数顺序
Overloading operators: operand order when using C++ literals
我正在写一个 class,我已经到了可以混合我的 class 类型对象和 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);
未涵盖,据我了解,文字本身不是 class 的对象。因此,整个表达式不可能。
我知道我可以创建用户定义的文字,但这不是我想在这里做的。 (虽然我不确定他们是否会工作)。
我在这个网站上找不到任何我应该相关的提示浏览问题,我在网上也找不到与我的问题相关的东西。
我的问题:
有什么方法可以使任一订单都有效吗?
您可以添加一个全局函数:
inline CLS operator+(const char *lhs, const CLS& rhs)
{
return CLS(lhs) + rhs;
}
此代码:
cout << "\n Good " + b; /* this is not possible because of the operands order */
不起作用,因为您创建了 operator+
成员(而不是 const 成员)。如果你将它重写为独立函数(可能是朋友)那么这个问题就会消失:
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 )
{}
它更清洁、更高效
我正在写一个 class,我已经到了可以混合我的 class 类型对象和 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);
未涵盖,据我了解,文字本身不是 class 的对象。因此,整个表达式不可能。
我知道我可以创建用户定义的文字,但这不是我想在这里做的。 (虽然我不确定他们是否会工作)。
我在这个网站上找不到任何我应该相关的提示浏览问题,我在网上也找不到与我的问题相关的东西。
我的问题:
有什么方法可以使任一订单都有效吗?
您可以添加一个全局函数:
inline CLS operator+(const char *lhs, const CLS& rhs)
{
return CLS(lhs) + rhs;
}
此代码:
cout << "\n Good " + b; /* this is not possible because of the operands order */
不起作用,因为您创建了 operator+
成员(而不是 const 成员)。如果你将它重写为独立函数(可能是朋友)那么这个问题就会消失:
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 )
{}
它更清洁、更高效