const成员函数

简介: 尽管函数名和参数列表都相同,void foo( ) const成员函数是可以与void foo( )并存的,可以形成重载! 我们假设调用语句为obj.foo(),如果obj为non-const对象,则调用foo()。

尽管函数名和参数列表都相同,void foo( ) const成员函数是可以与void foo( )并存的,可以形成重载! 我们假设调用语句为obj.foo(),如果objnon-const对象,则调用foo()。如果objconst对象,则调用foo()const。另外要注意,假如没有提供foo()const,则const obj调用foo()将会报错。但假如是没有提供foo(),则non-const obj调用foo()const是完全没有问题的。也就是说,non-const对象可以调用const函数(当然也可以调用non-const函数),但const对象不能调用non-const函数

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

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

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

//Only member functions declared as const can be invoked for a class object that is const. The const keyword is placed between the parameter list and the body of the member function. A const member function defined outside the class body must specify the constkeyword in both its 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];

}

原文

http://www.cnblogs.com/visayafan/archive/2011/11/24/2261849.html

目录
相关文章
|
2月前
|
C++ 开发者
43运算符重载函数作为类成员函数和友元函数
43运算符重载函数作为类成员函数和友元函数
17 0
|
2月前
|
编译器 C++
由临时对象引发的对常引用的思考
由临时对象引发的对常引用的思考
21 0
|
8月前
|
存储 编译器 C++
28 C++ -this指针
28 C++ -this指针
22 0
|
10月前
|
编译器 程序员
成员函数
成员函数
|
2月前
|
Java C++
This指针
This指针
30 0
|
2月前
|
C++
C++程序中的类成员函数
C++程序中的类成员函数
24 1
|
2月前
|
存储 编译器 对象存储
【C++】类与对象(构造函数、析构函数、拷贝构造函数、常引用)
【C++】类与对象(构造函数、析构函数、拷贝构造函数、常引用)
15 0
|
2月前
|
存储 编译器 C++
【c++】this指针
【c++】this指针
【c++】this指针
|
2月前
友元函数、成员函数和普通函数使用上的不同
友元函数、成员函数和普通函数使用上的不同
9 0
|
2月前
|
C++
c++类与对象(五):友元、内部类、临时对象、匿名对象
c++类与对象(五):友元、内部类、临时对象、匿名对象
26 0