+运算符,类类型和内置类型之间的区别?

Jam*_*Fan 17 c++ const function object operator-keyword

我是C++的新手.我读过的这本书告诉我,如果+为某个类对象(比如类)重载了plus()运算符,那么string这个问题会更加具体.

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s1("abc");
    string s2("def");

    string s3("def");

    cout<<(s1+s2=s3)<<endl;

    int x=1;
    int y=2
    int z=3;
    cout<<(x+y=z)<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如您所料,第一个cout陈述是正确的,而第二个陈述是错误的.编译器投诉x+y不是可修改的左值.我的问题是为什么+操作符为string对象返回可修改的左值但不是为了int

M.M*_*M.M 20

它不会为字符串返回可修改的左值.它返回一个临时对象,s1+s2并且x+y都是rvalues.

但是,类类型的对象可能已经过载operator=,这样string做.您可以在rvalues上调用成员函数.

这两种情况的区别在于=(不是+)


Jar*_*d42 14

因为std::string,s1 + s2 = s3实际上是:

(operator+(s1, s2)).operator =(s3)
Run Code Online (Sandbox Code Playgroud)

s1 + s2 返回一个右值

成员方法也可以应用于临时.
从C++ 11开始,我们有方法的左值/右值限定符,
因此您可以禁止使用o1 + o2 = o3以下自定义类型:

struct Object
{
    Object& operator =(const Object& rhs) & ; // Note the & here
};
Run Code Online (Sandbox Code Playgroud)

所以Object::operator =只能应用于左值.