1.有const修饰的成员,构造函只能以成员列表方式赋值,只能读取数据成员,不能改变数据成员;
//有const修饰的成员,构造函只能以成员列表方式赋值,只能读取数据成员,不能改变数据成员;
#include<iostream>
using namespace std;
class Time {
public:
const int hour;
const int minute;
const int second;
Time (int h,int m,int s):hour(h),minute(m),second(s){}
//有const修饰的成员,构造函只能以成员列表方式赋值
/*Time(int h,int m,int s) {
hour = h;
minute = m;
second = s;
}*/
//错误,只能用成员列表的方式赋值
void Show() {
cout << hour << ":" << minute << ":" << second;
}
};
int main()
{
Time t(1, 2, 3);
t.Show();
//不能改变数据成员
//t.hour = 10;//错误
return 0;
}
2.在类的成员函数后面加 const,常函数,只能引用不能改变成员变量的值,可以被const对象调用。
//在类的成员函数后面加 const,常函数,只能引用不能改变成员变量的值,可以被const对象调用。
#include<iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void fun()const {
//只能引用
cout << hour << ":" << minute << ":" << second << endl;
//不能改变成员变量的值
//minute = 0;//错误
}
void Show() {
cout << hour << ":" << minute << ":" << second << endl;
}
};
int main()
{
const Time t(10,11,12);
//可以被const对象调用
t.fun();
//不可以被非const对象调用
//t.Show();//错误,该函数是非const函数,常对象只能调用const函数
return 0;
}
3.const修饰对象 叫常对象,只能调用const成员函数,无法调用非const成员函数。
//3.const修饰对象 叫常对象,只能调用const成员函数,无法调用非const成员函数。
#include<iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void fun()const {
cout << hour << ":" << minute << ":" << second << endl;
}
void Show() {
cout << hour << ":" << minute << ":" << second << endl;
}
};
int main()
{
const Time t1(10,11,12);//常对象
//常对象可以被const对象调用
t1.fun();
//常对象不可以被非const对象调用
//t1.Show();//错误,该函数是非const函数,常对象只能调用const函数
Time t2(20, 21, 22);//非常对象
//非常对象可以被const对象调用
t2.fun();
//非常对象可以被非const对象调用
t2.Show();
return 0;
}
PS:总结
数据成员 | 非const的普通成员函数 | const成员函数 |
非const的普通数据成员 | 可以引用,也可以改变值 | 可以引用,但不可以改变值 |
const数据成员 | 可以引用,但不可以改变值 | 可以引用,但不可以改变值 |
const对象 | 不允许引用 | 可以引用,但不可以改变值4 |
4.mutable 修饰变量可以改变。
//4.mutable 修饰变量可以改变。
#include<iostream>
using namespace std;
class Time {
private:
//定义mutable变量
mutable int hour;
int minute;
int second;
public:
Time(int h,int m,int s) {
hour = h;
minute = m;
second = s;
}
void Show()const {
//const函数中,mutable修饰的变量可以修改
hour = 20;
//const函数中,非mutable修饰的变量不可以修改
//second = 6;//错误
cout << hour << ":" << minute << ":" << second << endl;
}
};
int main() {
Time t(1,2,3);
t.Show();
return 0;
}