【发布时间】:2020-08-05 14:04:05
【问题描述】:
当我跳入现有代码并错误地使用 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;
}
所以我的问题有两个方面:
-
b.getAbyVal() = A{7};与b.getXbyVal() = 3;有什么不同,所以前者编译而后者不编译(除了类型是A和int)? - 将
void operator=(A const& other) { x = other.x; }更改为void operator=(A const& other) & { x = other.x; }会使b.getAbyVal() = A{7};无法编译。为什么会这样?
【问题讨论】:
-
在
A& getAbyRef()中,&属于返回类型A&。在void operator=(A const& other) &中,它充当引用限定符,并且与返回类型无关。&的这两种用法没有可比性。 -
void operator=通常返回类型是对对象的引用。就个人而言,我更喜欢像您在这里一样返回void进行分配,但这不是惯用的C++。如果您的团队愿意返回void,一切都很好。 -
@Eljay,不,我的团队不在船上,但我认为返回
void会帮助我(以及问题的读者)减少显式参数类型之间的混淆,隐式参数 @ 987654341@,以及返回值。
标签: c++ this getter return-by-reference return-by-value