我在C++中的一样预订了以下内容:超载基于L-值与R值
虽然我们不会在这本书中这样做,你可以重载一个 函数名(或经营)因此当使用 作为l值并将其用作r值时,它的行为会有所不同。 (请记住,l值意味着它可以在分配 语句的左侧使用。)例如,如果要函数f以 的行为不同,具体取决于它是否用作l值或 r值,你可以这样做如下:
class SomeClass {
public:
int& f(); // will be used in any l-value invocation const
const int& f() const; // used in any r-value invocation ...
};
我尝试这样做,也没有工作:
class Foo {
public:
int& id(int& a);
const int& id(int& a) const;
};
int main() {
int a;
Foo f;
f.id(a) = 2;
a = f.id(a);
cout << f.id(a) << endl;
}
int& Foo :: id(int& a) {
cout << "Bar\n";
return a;
}
const int& Foo :: id(int& a) const {
cout << "No bar !\n";
return a;
}
有我错误地理解了吗?
AFAIK函数重载不会因仅返回类型而有所不同 –
@PaulRenton:不,但它们可以在常量上有所不同,如代码所示。 – rodrigo