Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重载运算符:使用C++;字面量 我正在编写一个类,我可以做一些操作来混合我的类类型对象和C++文字,但是只在一个方向上。_C++_Operator Overloading_Literals_Operand - Fatal编程技术网

重载运算符:使用C++;字面量 我正在编写一个类,我可以做一些操作来混合我的类类型对象和C++文字,但是只在一个方向上。

重载运算符:使用C++;字面量 我正在编写一个类,我可以做一些操作来混合我的类类型对象和C++文字,但是只在一个方向上。,c++,operator-overloading,literals,operand,C++,Operator Overloading,Literals,Operand,下面是一个简化的代码,展示了这个想法: #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

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

#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 */
}
但不是,

"W" + a;
如代码最后一行所示

我明白原因

第一个相当于:

a.operator+("W");
这是我的课。但是第二个就是,

"W".operator(a);
这是没有涵盖和文字本身不是一个类的对象,因为我理解。因此,表达式作为一个整体是不可能的

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

我在这个网站上找不到任何提示,也找不到与我的问题相关的信息

我的问题:


是否有一种方法可以使任一订单都有效?

您可以添加一个全局函数:

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 */
如果您创建接受
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 )
{}

更干净、更有效的方法是

+
这样的二进制运算符通常应该是自由函数,而不是成员,在这种情况下,问题就消失了,因为可以对左侧和右侧操作数执行适当的转换。
CLS运算符+(const-CLS&lhs,const-CLS&rhs)
就足够了,因为没有接受
const char*
friend 
CLS operator+(const CLS& lhs, const CLS& rhs)
{
    return CLS( lhs.str + rhs.str );
}
CLS(const char* param) : str( param )
{}