⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo_7_const_member_1.cpp

📁 对于一个初涉VC++的人来书
💻 CPP
字号:

//***************************************************
//常成员函数: 
//      类型说明符 函数名(参数表) const;
//函数原型声明和函数定义实现两个部分都要带const关键字。
//常成员函数不能更新数据成员,也不能调用非const成员函数。
//常对象只能调用其常成员函数(唯一对外接口),而不能调用其它成员函数。
//const关键字可以参与重载函数的区分。
//***************************************************

# include <iostream.h>

class R
{
public:
	R(int r1, int r2):R1(r1),R2(r2) {}
	void print(); //const关键字可以参与重载函数的区分
	void print() const;
private:
	int R1,R2;
};

void R::print()
{   
	cout<<"calling general member function:";
	cout<<R1<<","<<R2<<endl;
}

void R::print() const
{   
	cout<<"calling const member function:";
	cout<<R1<<","<<R2<<endl;
}

void main()
{
	R a(5,4);          //类一般对象声明并初始化
	a.print();         //类一般对象调用非const成员函数

	const R b(20,52);  //类const对象声明并初始化
//	R const b(20,52);  //等价
	b.print();         //类const对象只能调用const成员函数
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -