在以下示例中:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
A是一个double的简单包装器,+并且=运算符已经过载.在以下用途中:
int main(int argc, char *argv[]) {
A a, b, c;
(a+b) = c ; // Why is this operation legal?
}
Run Code Online (Sandbox Code Playgroud)
为什么(a+b) = c编译?我想知道为什么这个陈述是合法的,因为结果(a+b)必须是一个rvalue.我没有从中返回参考operator+.
一段时间以来,我似乎无法解决这个特定问题。例如,如果我有以下代码:
void foo(std::vector<int>::iterator &it) {
// ...
}
int main(){
std::vector<int> v{1,2,3};
foo(v.begin());
}
Run Code Online (Sandbox Code Playgroud)
我会得到编译错误:
initial value of reference to non-const must be an lvalue.
Run Code Online (Sandbox Code Playgroud)
我的猜测是我收到错误,因为a.begin()返回了一个右值。
如果是这样,以下表达式怎么可能起作用:
v.begin()=v.begin()++;
Run Code Online (Sandbox Code Playgroud)
如果v.begin()是右值?
假设我有一个带有重写赋值运算符的类:
class Test
{
public:
Test& operator =(const Test&) {return *this;}
};
Test f();
Run Code Online (Sandbox Code Playgroud)
有没有办法让它成为编译时错误来分配函数的结果?
例子:
f() = test();
Test t;
f() = t;
// if there were also a Test Test::operator+(Test);
(t + t) = test();
Run Code Online (Sandbox Code Playgroud)
原始类型已经发生这种情况,我想为这个类复制它:
int g();
g() = 5; // error
(3 + 4) = 5; // error
Run Code Online (Sandbox Code Playgroud)
编辑:我使用的是Visual C++,它不支持所有的C++ 11.具体来说,它不支持ref-qualifiers.