0
点赞
收藏
分享

微信扫一扫

常对象与常成员函数

慕容冲_a4b8 2022-03-18 阅读 189
c++蓝桥杯
#include<iostream>
using namespace std;
class time1
{
public:
	time1(int a, int b, int c) :hour(a),min(b),sex(c) {}
	void display();
	void show()const;//常成员函数
	void set(int a, int b, int c) {
		hour = a;
		min = b;
		sex = c;
	}
private:
	 int hour, min, sex;
	 //const int m;  常变量 只能在构造函数中用用初始化列表来初始化,例如:time1( int a) :m(a){}
};

void time1::display()
{
	cout << hour << ":" << min << ":" << sex << endl;
}
void time1::show() const
{
	cout << hour << ":" << min << ":" << sex<<endl;
	//this.hour = 1;报错。不可改变值
	//常成员函数只能引用本类中的数据成员,而不能修改.
}

int main() {
	const time1 t1(10, 20, 55);
	//t1.display();      报错、 常对象只能调用常成员函数
	t1.show();
	//t1.set(10,20,30);      报错,常对象不能被修改;
	time1 t2(1, 52, 33);
	t2.display();
	t2.set(21, 32, 33);
	t2.show();
	
	return 0;


}

注释挺全的,看注释的吧。

补充一个表 

 

举报

相关推荐

0 条评论