C++ 常数据成员、常成员函数和常对象

首先给出一个例子简单理解const修饰数据变量的基本工作原理:

#include <stdio.h>

int main()
{
	const int a = 250;
	int *ptr = (int *)&a;
	*ptr = 360;
	printf("*ptr = %d\n",*ptr); 
	printf("ptr = %p\n",ptr); 
	printf("a = %d\n",a);
	printf("&a = %p\n",&a);
	return 0;
} 

运行结果:

从运行结果来看,显然我们队地址所指向内存的数据的修改并没有作用到a身上,这也就从另外一方面直接表明了对a的访问不是通过访问内存的方式。

那么这里const对int a的修饰可以理解为#define a 250 ,但是使用const还可以保存相应的数据类型信息(a++==251)

 

接下来主要讲到const对C++中类的成员以及对象的修饰:

************************************************************************************************************************************

 

一:常数据成员

1. 首先我们定义一个Point类:

class Point
{
private:
	int x, y;
	const int e;
	static int count;
public:
	Point(int xx, int yy,int ee):e(ee),x(xx),y(yy)
	{
		count++;
	}
	void Show_C()
	{
		cout << "C = " << c << endl;
		//cout << "D = " << d << endl;  //这里就已经没有访问权限了
	}
	static int Show_Count()
	{
		return count;
	}
	int c = 250;
	const int d = 360;    //可以直接在声明的时候赋值
};

① 我们可以在定义const变量的时候直接对其进行赋值,赋值过后便无法再对它进行各种"计算"操作;

② 如果不在定义的时候赋值,那就需要在该类的构造函数中使用初始化列表进行赋值(初始化):

  

在类的一般函数成员中依然可以访问const类型的数据成员。

那常成员函数有什么用呢?

 

 

二:常成员函数

① 首先,常成员函数内部不允许进行数据成员的修改,但是可以在函数内部输出const数据成员与非数据成员!

② 其次,还可以区分同名构造函数,举个例子(如下):

#include <iostream>
using namespace std;

class Test
{
public:
	void Show()const
	{
		cout << "Hello,Const!" << endl;
	}
	void Show()
	{
		cout << "Hello!" << endl;
	}
};

int main()
{
	Test t1;
	t1.Show();
	Test const t2;
	t2.Show();
	return 0;
}

 

 

三:常对象

在类的实例化同时,加上const进行修饰实例化出的对象即可:

const修饰对象,直接限制了对象对其内部非const成员的访问,也就是说如果类中的数据成员与函数成员都没有被const修饰,

那么实例化出的对象将无法对类进行操作;

当然,const对象是可以直接操作const成员的(数据成员、函数成员),所以这就需要我们把成员函数声明为const型;

#include <iostream>
using namespace std;

class Point
{
private:
	int x, y;
	const int e;
	static int count;
public:
	Point(int xx, int yy,int ee):e(ee),x(xx),y(yy)
	{
		count++;
	}
	void Show_C()const   //常函数内部无法对数据进行修改
	{
		cout << "C = " << c << endl;
		cout << "D = " << d << endl;
	}
	static int Show_Count()
	{
		return count;
	}
	int c = 250;
	const int d = 360;    //可以直接在声明的时候赋值
};

int Point::count = 0;

int main()
{

	Point const P1(1, 2, 3);    //这里的const直接限制了在外部对类中public中数据成员的修改

	cout << P1.d << endl;    //const int d = 360;

	P1.Show_C();

	return 0;
}

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值