const关键字

1.const定义常量(和#define)的区别:

const int a=10;
发生时机:编译,它就会有语法检查,如果定义常量,推荐使用

#define a 10
发生时机:预处理,只是一个简单的字符串替换(宏出错的话并不能意识到已经发生了错误)

2.const 修饰指针的两种形式:

常量指针(pionter to const):

const int *pa=&b;
*pa=110;//Error 指针所指向的变量是不能修改的
pa=&c;//可以修改其指向
指针常量(cosnt pointer)

int * const pa =&b;
*pa=110;//指针可以修改其指向的值
pa=&c;//指针本身的值不能被修改
可以用来保护被修饰的东西,增强程序的健壮性

3.const成员函数:把const  放在函数的参数体和函数体中。

   它的特点有两个,一个是只能读取数据成员而不能修改它,另一个是只能调用const成员函数,而不能调用非const成员函数

   其基本格式为:类内定义时:

     类型  函数名(参数列表)const

     {

             函数体;

     }

     类外定义时:

     类型  类名::函数名(参数列表)const

    {

             函数体;

    }

    

#include <iostream>
using namespace std;

class point
{
	int x; //默认为private的数据成员x和y
	int y;

public:
	point(int xp = 0, int yp = 0) //构造函数
	{
		x = xp;
		y = yp;
	}

	void print() const //const成员函数内无法修改数据成员,否则编译器报错
	{
		x = 5; //1. 试图修改x将引发编译器报错
		set(); //2. 试图调用非const函数将引发编译器报错
		cout << "x: " << x << " ,y: " << y << endl;
	}

	void set() //将set()定义成const函数就能解决问题
	{
	}
};

int main()
{
	point pt;		//声明类对象,以缺省参数形式调用构造函数
	pt.print();		//调用const成员函数

	return 0;
}


c++类常量无法调用非const成员函数,若想调用,则必须在成员函数上加上const

#include<iostream>
using namespace std;
class A {
private:
	int x;
	int y;
public:
	void print() {          // 必须加上const ,否则a无法调用
		cout <<x<< endl;
	}
};
int main() {
	const A a;
	a.print();//a是无法调用非const成员函数
	return 0;
}

在const成员函数中不允许修改对象的数据,也不允许调用非const成员函数(因为这样会间接的修改对象的数据,所以被C++封了),这样的函数是如下声明的:

class A  
{  
    int function(int para)  const; //我们看到的const成员函数  
    int function(const A *this, int para) //编译器的const成员函数  
}  


所以一个类的尾后const成员函数如果返回*this,那么其返回类型必然是 const 类名 & 前面这个const是不能少的.否则无法通过编译


class B {
public:int v;
         //B &get() const 这样声明是错误的
	   const B &get() const {
		 //const成员函数返回*this必须是const的引用
		   return *this;
	   }
};



4.修饰类成员变量

用const修饰的类成员变量,只能在类的构造函数初始化列表中赋值,不能在类构造函数体内赋值。

#include <iostream>
using std::cout;
using std::endl;

class Point
{
public:
	explicit
	Point(int ix = 0, int iy = 0)
	: _ix(ix) //对于const数据成员,只能初始化列表之中进行
	, _iy(iy)
	{
		cout << "Point(int,int)" << endl;
		//_ix = ix;这样为赋值,报错
		//_iy = iy;
	}

	void print()
	{
		cout << "(" << _ix
			 << "," << _iy
			 << ")" << endl;
	}
private:
	const int _ix;
	const int _iy;
};


int main(void)
{
	Point pt(1, 2);
	pt.print();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值