C/C++沉思-----const的简单用法

一 const与指针

1  指针常量 

int*const ptr

指针常量,即不可以将ptr修改为指向内存中另一处的地址,但可以用它来改变它所指向的地址处的数据内容。

//const.cpp
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
	int temp = 4;
	cout << temp << endl;

	//ptr被const修饰 定义时必须初始化
	int *const ptr = &temp;
	*ptr = 5;
	cout << temp << endl;

	return 0;
}

程序运行截图:

 

2 常量指针

const int *ptr;    (常量指针的另一种写法int const *ptr)

常量指针,即可以将ptr修改为指向内存中另一处的地址,但不可以用它来改变它所指向的地址处的数据内容。

//const.cpp
#include <iostream>
#include <cstring>
using namespace std;

int main()
{

	int temp1 = 4;
	int temp2 = 5;

	const int *ptr;
	ptr = &temp1;
	cout << "*ptr:" << *ptr << endl;

	ptr = &temp2;
	cout << "*ptr:" << *ptr << endl;

	return 0;
}


 

程序运行截图:

 

指向const常量的const指针

const int *const ptr;   (另一种写法int const *const ptr

指向const常量的const指针,即ptr所指向的内存地址和所指向的地址处的数据内容都不能被修改

 

PSconst离谁比较近,则谁的值不能被改变

 

 

二  const与函数

1 const修饰函数的参数

const使该参数在函数中不能被改变

void copy(char *strDes, const char *strsrc)

strsrc指针所指向的值在copy函数中不能被改变,如果意外的改动该指针,编译器会报错

 

注意:

不用将“值传递”的方式(void copy(int x, in y))加const修饰,因为函数会自动产生临时变量用于复制该参数,参数本来就不需要保护。

 

2 const修饰函数的返回值

const int* add(int x, int y);

add函数的返回值(即指针)的内容不能被修改,该返回值只能被赋值给加const修饰的同类型指针

const int *p = add(3, 5);

 

注意:

如果函数返回值是“值传递方式”(int add(int x, int y),由于函数会把返回值复制到外部临时的存储单元中,加const修饰没有意义。

 

3 const成员函数

任何不会修改类的数据成员(即函数中的变量)的函数都应该声明为const类型。在编写const成员函数时,如果不小心修改了数据成员,或者调用了其他非const成员函数,编译器会报错,这种做法将大大提高程序的健壮性。

//test.cpp
class test
{
public:
	void set(int);
	//const成员函数
	int get()const;        
private:
	int value;
};

int test::get()const
{
	//编译错误 修改数据成员value
	++value;
	//编译错误 调用了非const函数
	set(5);
	return value;
}


 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值