有这样的代码:
#include <iostream>
#include <string>
int returnnumber() { return 2; }
std::string returntext() { return "siema"; }
int main() {
std::cout << (returntext() += "cze") << std::endl; // siemacze
//std::cout << (returnnumber() += 2) << std::endl; error: lvalue required as left operand of assignment
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么可以更改std :: string的返回值,而不是int?
Che*_*Alf 10
因为std::string是具有已定义+=运算符作为成员函数的类类型.
并且标准允许您在rvalues上调用成员函数.
这是一个愚蠢的结果
struct S { int x; };
S foo() { return S(); }
int main()
{
foo() = S(); // OK, uses member assignment operator.
foo().x = 666; // !Nah, can't assign to rvalue of built-in type.
}
Run Code Online (Sandbox Code Playgroud)
编译结果:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions
"ComeauTest.c", line 7: error: expression must be a modifiable lvalue
foo().x = 666; // !Nah, can't assign to rvalue of built-in type.
^
1 error detected in the compilation of "ComeauTest.c".
然而,编制者对于他们如何严格地应用这一微妙的规则,或者根本不同,有所不同(或曾经不同).
干杯和hth.,