简体   繁体   English

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

[英]The + operator, difference between class types and built-in types?

I'm new to C++. 我是C ++的新手。 The book I read tells me that if the plus ( + ) operator has been overloaded for some class object, say, the string class, to make this problem more concrete. 我读过的这本书告诉我,如果加号( + )运算符已经为某个类对象(比如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;
}

As you may expect, the first cout statement is correct while the second is wrong. 正如您所料,第一个cout语句是正确的,而第二个是错误的。 The compiler complaints x+y is not a modifiable lvalue. 编译器投诉x+y不是可修改的左值。 My question is why the + operator returns a modifiable lvalue for string objects but not for int ? 我的问题是为什么+运算符为string对象返回一个可修改的左值但不为int

It does not return a modifiable lvalue for string. 它不会为字符串返回可修改的左值。 It returns a temporary object, and s1+s2 and x+y are both rvalues. 它返回一个临时对象, s1+s2x+y都是rvalues。

However, objects of class type may have overloaded operator= , which string does. 但是,类类型的对象可能具有重载的operator= ,即string You are allowed to call member functions on rvalues. 您可以在rvalues上调用成员函数。

The difference between the two cases is in = (not + ) 这两种情况之间的区别在于= (未+

For std::string , s1 + s2 = s3 is in fact: 对于std::strings1 + s2 = s3实际上是:

(operator+(s1, s2)).operator =(s3)

s1 + s2 returns a rvalue s1 + s2返回一个右值

Member methods can be applied to temporary also. 成员方法也可以应用于临时。
Since C++11, we have the lvalue/rvalue qualifier for method, 从C ++ 11开始,我们有方法的左值/右值限定符,
so you may forbid o1 + o2 = o3 for your custom type with: 所以你可以禁止o1 + o2 = o3为你的自定义类型:

struct Object
{
    Object& operator =(const Object& rhs) & ; // Note the & here
};

so Object::operator = can only be applied to lvalue. 所以Object::operator =只能应用于左值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM