1.问题
笔者在阅读C++代码时,看到类似如下图所示的代码
#include <iostream>
using namespace std;
class Person {
private:
string name_;
int age_;
public:
string& Name();
int& Age();
string Name() const;
int Age() const;
Person(string name, int age) {
name_ = name;
age_ = age;
}
};
string& Person::Name() {
return name_;
}
int& Person::Age() {
cout << "lv" << endl;
return age_;
}
string Person::Name() const {
return name_;
}
int Person::Age() const {
cout << "rv" << endl;
return age_;
}
int main() {
Person person1("zhangsan", 11);
person1.Age() = 12;
int age = person1.Age();
cout << age << endl;
return 0;
}
在Person类中Name()、Age()方法均被声明了两遍,并且函数返回值可以做为左值
上述程序执行的结果
lv
lv
12
2.笔者的思考
“person1.Age() = 12”执行了“int& Age()”函数,这个函数的返回值为int&,可做为左值(笔者觉得在执行这个函数,返回值是该类对象成员变量的引用,也就是可以取得该成员变量的地址,自然可以做为左值)
“int age = person1.Age()”执行了“int& Age()”函数,但笔者怀疑这个行为不同的编译器行为不同,有可能其他编译器会执行“int Age() const”函数