这是把整个函数修饰为const,意思是“函数体内不能对成员数据做任何改动”。如果你声明这个类的一个const实例,那么它就只能调用有const修饰的函数。
如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class
Text{
public
:
void
printconst(
void
)
const
{cout<<
"hello"
<<endl;}
void
print(
void
){cout<<
"hello"
<<endl;}
private
:
int
k;
};
const
Text a;
//上面定义了类Text的一常量对象
int
main(
void
)
{
a.printconst();
//ok
a.print();
//error
//上面a.print()调用是非法的
return
0;
}
|
const对象只能调用const成员函数。 const对象的值不能被修改,在const成员函数中修改const对象数据成员的值是语法错误 。 在const函数中调用非const成员函数是语法错误
声明一个成员函数的时候用const关键字是用来说明这个函数是 "只读(read-only)"函数,也就是说明这个函数不会修改任何数据成员(object)。 为了声明一个const成员函数, 把const关键字放在函数括号的后面。声明和定义的时候都应该放const关键字。
任何不会修改数据成员的函数都应该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其它非const成员函数,编译器将指出错误,这无疑会提高程序的健壮性。
#include <iostream.h>
class temp
{
public:
temp(int age);
int getAge() const;
void setNum(int num);
private:
int age;
};
temp::temp(int age)
{
this->age = age;
}
int temp::getAge() const
{
age+=10; // #Error...error C2166: l-value specifies const object #
return age;
}
void main()
{
temp a(22);
cout << "age= " << a.getAge() << endl;
}
因为声明了const函数,所以不可以修改任何数据成员,但是在这里给age数据成员加了10, 所以产生错误。