#const 关键字在C++类中的用法
const 在修饰一个变量的时候相当于将这个变量变为常量,如果再对它的值 进行改变则属于非法操作,下面的代码是const关键字对类修饰所需要注意的事项,如果不添加const类虽然也可以照常运行,但是不利于数据的保护。
下面是一个时间类,通过对24小时的时间进行加减操作以及取值和赋值操作简单介绍const在类中的用法。
#include<iostream>
using namespace std;
class time24
{
public:
time24(int h=0, int m=0, int s=0) :hours(h), minutes(m), seconds(s)
{}//构造函数,初始化列表
void get_time(int &h, int &m, int &s)const;//对时钟取值
//调用的对象内的数据不可改变,因为加入了const,对get_time()进行限制
//get_time()函数对类成员变量hours,minutes,seconds的值不能改变
void set_time(int h,int m,int s);//对时钟进行赋值
//没有加const也不能加const,因为set_time()函数目的就是改变成员变量
//的值,因此不能加
time24 operator+(int i)const;//调用的对象内的数据不可改变
//因为加了const函数,主调函数的成员变量不能改变
time24 operator+(const time24 &t2)const;
//调用的对象以及作为实参的对象内的数据均不可被改变
//此处有两个const,参数列表里的const对t2进行保护,t2成员变量不能更改
//而写在外面的const是保护主调函数的成员变量不能更改。
//在此处两个const是为了在两个时间相加时,如a=b+c
//在计算时b,c都不能被改变,值返回a即该函数返回一个time24。
private:
int hours;//时
int minutes;//分
int seconds;//秒
};
void time24::get_time(int &h, int &m, int &s)const
{
h = hours;
m = minutes;
s = seconds;
}
void time24::set_time(int h, int m, int s)
{
hours = h;
minutes = m;
seconds = s;
}
time24 time24::operator+(int i)const
{
time24 t;
t.seconds = seconds + i;
t.minutes =minutes + t.seconds/60;
t.seconds %= 60;
t.hours = hours + t.minutes / 60;
t.minutes %= 60;
t.hours %= 24;
return t;
}
time24 time24::operator+(const time24& t2)const
{
time24 t;
t.seconds = seconds + t2.seconds;
t.minutes = minutes + t2.minutes+t.seconds / 60;
t.seconds %= 60;
t.hours = hours + t2.hours+t.minutes / 60;
t.minutes %= 60;
t.hours %= 24;
return t;
}
int main()
{
int h, m, s;
time24 t3,t4;//若此前加入const,则下面t4,t3不能进行赋值运算,因为此时t4,t3不可变,相当于常量
const time24 t1(23,59,57), t2;
//若加上const,则time24不能被改变,则不可调用set_time()
//因为如果对象前加上const,则对象只能调用带const的对象成员函数以保护象
//(如果不加const,即使没有改变成员函数的值也不行)
//而set_time()函数不能加const,因为函数本身就是用于改变对象数据的值
t4 = t1 + 3;
t4.get_time(h, m, s);
cout << h << ":" << m << ":" << s<< endl;
t3 = t1 + t2;
t3.get_time(h,m,s);
cout << h << ":" << m << ":" << s;
}
总结
const修饰类函数后,则函数不能改变类成员变量
const修饰参数变量时,参数的值不能被改变(通常使用const &搭配,在传 地址的时候保护参数,传参避免了复制,也保护了参数)
被const修饰的对象只能调用由const修饰的成员函数以对对象进行保护