1 范例分析
/*----------------test.h----------------*/
#include <iostream>
using namespace std;
class ttclass
{
public:
/*重载1:
[1] 采用schme-A时,“重载1”和“重载2”可正常执行;
[2] 采用scheme-B时,程序将报错!!!
*/
int get_aa() const /*scheme-A*/
//int get_aa() /*scheme-B: */
{
cout<<"Now is get_aa(), a="<<a<<endl;
return a;
}
/*重载2:
作用:由于该函数返回值为类成员变量a的引用,故可将函数get_aa作为左值进而修改类成员变量a的数值!
*/
int& get_aa()
{
cout<<"Now is get_aa(Reference), a="<<a<<endl;
return a;
}
int a;
};
/*----------------test.cpp----------------*/
#include "test.h"
int main()
{
ttclass kk;
kk.a=100;
kk.get_aa(); //重载1
cout<<" [1] aa="<<kk.a<<endl;
kk.get_aa()=999; //重载2
cout<<" [2] aa="<<kk.a<<endl;
return 1;
}
采用g++
编译
g++ -std=c++11 test.cpp -o kk
> ./kk
Now is get_aa(Reference), a=100
[1] aa=100
Now is get_aa(Reference), a=100
[2] aa=999
从上述结果可知,
重载2
作为左值时,确实可以修改类成员变量a
的数值!
2 为何scheme-1不报错呢?
因为采用
scheme-1
时,实际上重载1
和重载2
有1个隐藏参数类型是不同的!
int get_aa() const
中的隐藏参数this指针类型为const this
;int& get_aa()
中隐藏参数this指针类型为this
;
因此,
schme-1
时,代码不报错!而scheme-2
时代码报错!