gpt4 book ai didi

c++ - 分配给右值 : why does this compile?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:32 25 4
gpt4 key购买 nike

在下面的例子中:

class A {
private: double content;

public:
A():content(0) {}

A operator+(const A& other) {
content += other.content;
return *this;
}

void operator=(const A& other) {
content = other.content;
}

};

A 是 double 的简单包装器,+= 运算符已被重载。在以下使用中:

 int main(int argc, char *argv[]) {
A a, b, c;
(a+b) = c ; // Why is this operation legal?
}

为什么(a+b) = c可以编译?我想知道为什么这个语句是合法的,因为(a+b ) 必须是 右值。我不会从 operator+ 返回引用。

最佳答案

(a+b) = c(a+b).operator=(c) 相同。赋值运算符中的右值引用没有特殊规则,它只是遵循通常的函数调用规则。如果你想阻止使用右值调用,你可以添加一个 ref-qualifier:

void operator= (const A& other) & {
// ^
content = other.content;
}

这将只允许在左值上调用函数。

关于c++ - 分配给右值 : why does this compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33784044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com