首先给出一个例子简单理解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;
}