重载运算符:使用C++文本时的操作数顺序
Overloading operators: operand order when using C++ literals
我正在编写一个类,我可以执行混合类类型对象和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;
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 控制允许动态运行c++的并发操作数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- QML按钮点击功能执行顺序
- C++评估顺序优化是否意味着对不同的操作数使用不同的内核?
- C++是否保证标准容器比较中操作数的顺序?
- 重载运算符:使用C++文本时的操作数顺序
- 与任何算术操作员都会影响优化的恒定操作数顺序
- *运算符重载中的操作数顺序
- 模数 - GCC 的操作数顺序错误?或 UB
- C语言中等优先级操作数的计算顺序
- 重载逗号操作符真的会影响其操作数的求值顺序吗?
- 操作数的求值顺序
- 与std::map相比,操作数的顺序