C++成员函数末尾const关键字…

来源:互联网 发布:南风知我意 书包网 编辑:程序博客网 时间:2024/06/05 05:17
原文地址:C++成员函数末尾const关键字的作用作者:olym

1>   尽管函数名和参数列表都相同,void   foo( )const成员函数是可以与void   foo( )并存的,可以形成重载 

我们假设调用语句为obj.foo(),如果obj为non-const对象,则调用foo()。如果obj为const对象,则调用foo()const。另外要注意,假如没有提供foo()const,则constobj调用foo()将会报错。但假如是没有提供foo(),则non-constobj调用foo()const是完全没有问题的。也就是说,non-const对象可以调用const函数,但const对象不能调用non-const函数:-)

2>const关键字所起作用的本质,就是把隐藏着的默认的this指针参数,改成const类型。也就是说:
假如void    foo()函数被编译器改写为 void foo(T* pThis),则void foo( ) const将会被改写为voidfoo(const T* pThis)。i.e. 在函数末尾添加一个const,就相当于在隐藏的this参数类型前加一个const.

这样做有两个效果,第一:编译器将不允许foo()const修改pThis指向的对象的成员。第二、const对象只能调用const成员函数,否则就会报错说把constT* 转化为T* 会丢失qualifier

----------------------------------

Only member functions declaredas const canbe invoked for a class object thatis const. The const keywordis placed between the parameter list and the body of the memberfunction. A const memberfunction defined outside the class body must specifythe constkeyword in bothits declaration and its definition. For example:

class Screen 
    public:     
    bool isEqual( char ch ) const;     // ...private:     
    string::size_type    _cursor;     
    string               _screen;     // ... 
}; 
bool Screen::isEqual( char ch ) const 
    
    return ch == _screen[_cursor]; 
}
0 0