类的成员函数后跟const。 这表示此函数不会对该类中对象的数据成员(准确地说是非静态数据成员)进行任何更改。
在设计类时,原则上不应将不更改数据成员的成员函数标记为const,将更改数据成员的成员函数标记为const。 因此,const关键字更清楚地限制了成员函数的行为。 具有const限定的成员函数(意味着const位于函数参数表之后,而不是函数之前或参数表中)只能读取数据成员,不能修改数据成员。 非常数限定的成员函数可对数据成员写入。
除此之外,在类的成员函数之后添加const有什么好处? 这意味着常量(const对象)可以调用const成员函数,而不是const以外的限定函数。 相反,这是不成立的,因为非常数类型的数据可以为常数类型的变量赋值。
看看下面完整的例子,然后再说明一点。
代码:
#include iostream
#包含字符串
用户命名空间STD;
类student {
公共:
Student () }
sudent (持续时间,int sc=0) ) ) ) )。
3360name(nm ),Score ) sc ) }
voidset _ student (常数,int sc=0) )。
{
name=nm;
score=sc;
}
const string get_name () const
{
返回名称;
}
int get_score () const
{
返回得分;
}
隐私:
字符串名称;
int score;
(;
//output student's name and score
void output _ student (常数) )。
{
cout student.get_name (
cout student.get_score () endl;
}
int main () )
{
studentstu('Wang ',85 );
output_student(stu;
}设计了具有}name和score的类Student。 有两个构造函数,一个用于设置成员数据的函数set_student (),一个用于获取名称和score的函数get_name ),另一个用于获取get_score )。 get_name (和get_score ) )后面有const,但不在set_student ) )之后。 (也不能有常数。
首先是一点闲话,为什么get_name ()前面也有const? 如果前后两个const都不存在,get_name ()将返回对专用数据成员name的引用,因此可以按如下方式更改专用成员name的值
代码:
studentstu('Wang ',85 );
stu.get_name ()='Li ); 也就是说,将name从原来的“Wang”更改为“Li”。 这不是我们想要的。 所以,在get_name ()前加上const来避免这一点。
那么,应该在get_name (和get_score ) )后面加上const的成员函数是否必须没有const限定? 是的,可以。 但是,作为代价,const对象将无法调用这两个非const成员函数。 例如
代码:
const string get_name (; //这两个函数都应该是常数型
int get_score (;
void output _ student (常数) )。
{
如果cout student.get_name(get_name (和get_score ) )是非const成员函数,则此语句和以下语句的调用是错误的
cout student.get_score () endl;
}参数student表示对const Student类型对象的引用,因此student不能调用set_student (等非const成员函数。 如果get_name ()和get_score ) )的成员函数也是非const类型,则上面的student.get_name ) )和student.get_score )的使用将是非法的,并且
因此,没有理由反对使用const。 添加const时,必须添加const,以便成员函数除了可以调用const以外的对象外,还可以调用const对象。
转载于:https://www.cn blogs.com/macchiato 1988-10-17/p/4778716.html