const的其他情况不在赘述,我说的这个是只能用于修饰成员函数,用处是向编译器声明用户不会更改传入变量,要注意的是一种情况,就是当类内有两个重名的函数,比如:void T:: print(const int&)const ; void T:: print(const int&) ; 这两个成员函数是不同的,因为第一个函数的签名是print(const int&)const, 第二个是print(const int &),然后再说一下调用情况,只有const修饰的对象才能调用第一个const函数,没有const的只能调用第二个。下面附上测试代码,写的比较糙,但是够用了
#include<iostream>
class T {
int x;
public:
T(int t):x(t){}
int gets() const{ return x; }
int gets() { std::cout << x; return x; }
};
int T::gets() {
return x;
}
int main(void) {
const T t(10);
t.gets();
system("pause");
return 0;
}