当我跳入现有代码并错误地使用 getter 设置属性时,我产生了这个疑问,
obj.getProp() = otherProp;
而不是调用setter,
obj.setProp(otherProp);
我没有意识到错误,因为编译或运行时没有错误;该任务导致无操作。
所以我想出了下面的例子,它输出337
:
#include <iostream>
struct A {
int x = 0;
A(int x) : x(x) {}
A(A& a) : x(a.x) {}
void operator=(A const& other) { x = other.x; }
};
struct B {
A a{3};
int x{3};
A getAbyVal() { return a; }
A& getAbyRef() { return a; }
int getXbyVal() { return x; }
};
int main() {
B b;
std::cout << b.a.x; // this and the other two cout print what I expect, but...
b.getAbyVal() = A{7}; // ... I expected this to fail at compilation time in the first place...
//b.getXbyVal() = 3; // ... just like this fails.
std::cout << b.a.x;
b.getAbyRef() = A{7};
std::cout << b.a.x;
}
所以我的问题是两个方面:
- in
b.getAbyVal() = A{7};
有什么不同b.getXbyVal() = 3;
使得前者编译而后者不编译(除了类型是A
and的事实之外int
)? - 更改
void operator=(A const& other) { x = other.x; }
为void operator=(A const& other) & { x = other.x; }
使b.getAbyVal() = A{7};
编译失败。为什么会这样?