您的位置:首页 > 编程语言 > C语言/C++

【C++】const成员函数的作用

2009-11-30 22:15 141 查看
class Pig
{
long _lx;
public:
Pig(const long& _x = 9) : _lx(_lx){}
void show(void)
{
cout < < "Pig的成员_lx: " < < _lx < < endl;
}
};

编译器会对上述声明中的show()函数加入一个隐晦的this指针,其声明类似如下:

void show(Pig* const this)
{
......
}

这样当类被实例化为对象变量后,show凭借上述this指针就可以参阅到其数据成员_lx!

但是当类被实例化为常型对象后,类的数据成员就具有了常量属性,这样的this指针就不能再参阅其类成员_lx了,因为语言规则不允许以非常型指针去访问常量!例如:

class Pig
{
long _lx;
public:
Pig(const long& _x = 9) : _lx(_x){}

void show(void)//未加const修饰!!!
{
cout < < "Pig的成员_lx: " < < _lx < < endl;
}
};

int main()
{
const Pig _p;

/*如下 "_p.show(); "语句将生成:
errorC2662:Pig::show ":不能将 "this "指针从 "const Pig "转换为 "Pig & "
*/
_p.show();//!不能通过编译!

_PAUSE;
return 0;
}

为解决上述问题,可把show()成员函数声明为常型成员函数,这样编译器将为show()函数插入新的this指针,类似声明如下:

void show(const Pig* const this) const//!!!
{
......
}

这个新的this指针将可以访问包括常量在内的数据类成员!

例如:

class Pig
{
long _lx;
public:
Pig(const long& _x = 9) : _lx(_x){}

void show(void)const//声明为常型成员函数!
{
cout < < "Pig的成员_lx: " < < _lx < < endl;
}
};

int main()
{
const Pig _p;//声明为常型对象!

_p.show();//行为良好!输出 "Pig的成员_lx: 9 " !

_PAUSE;
return 0;
}

以上就是成员函数后面加const的原因!

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/weiweitj/archive/2008/04/19/2307883.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: