C++的const指针的使用注意事项

  1. const关键字在C++中表示常量的意思,但是const的使用很容易使人混淆,特来一记,便于以后查阅。
  2. const int a = 11;
    
    //a = 5;//不能给常亮赋值
    int b = 5;
    cout << “b=” << b << endl;
    int *p = &b;
    *p = 10;//非const指针可以通过赋值的方式修改b的值。
    cout << “b=” << b << endl;

带上const的指针
第一种形式:
const int a = 11;
//a = 5;//不能给常亮赋值
int b = 5;
int c = 10;
int d = 20;
cout << “b=” << b << endl;
const int *point = &b;
cout << “*point=” << *point << endl;
//*point = 10;//point不能给常量赋值。解释为定义指向常量的指针point ,可以改变指针的指向,但是不能通过指针来改变 x中的值,代码如下:
cout << “b=” << b << endl;
point = &d;
cout << “*point=” << *point << endl;

第二种形式:
int bb = 22;
int dd = 44;
int *const p2 = &bb;
cout << “*p2=” << *p2 << endl;
*p2 = 33;
cout << “*p2=” << *p2 << endl;
cout << “bb=” << bb << endl;
//p2 = ⅆ//p2不能给常亮赋值。解释定义常指针p2,不可改变指针的指向(常指针),但可以通过指针来修改x中的值

第三种形式:
int d1 = 55;
int d2 = 66;
const int *const p3 = &d1;
//*p3 = 78;p3不能给常亮赋值
//p3 = &d2;p3不能给常亮赋值,这种形式的指针不可以修改指针的指向,也不能修改通过指针修改变量的值
这些记忆网上总结了一些很好的记忆方法:
理解const 这些声明的技巧在于,查看关键字const右边来确定什么被声明为常量 ,如果该关键字的右边是类型,则值是常量;如果关键字的右边是指针变量,则指针本身是常量。
const在函数的入参的保护方面有很大的作用;
const修饰函数参数
void getmaxnum(const int a)
{
//a = 15;入参加了const,防止函数内部对其进行修改。保护入参。
}

在类的函数中存在const的类函数和成员变量。用来保护类成员不被修改。mutable修饰的成员变量可以突破const的限制
class Test
{
public:
Test()
{

}
int getx()const
{
	//x = 11;在const函数中,不允许修改任何成员变量
	//add();const函数中无法调用非const函数,因为非const函数可以修改成员变量;
	z = 10;//mutable修饰的成员变量可以突破const的限制
	return x;
}
int gety()
{
	add();
	return y;
}
void add()
{
	sum = x + y;
}

private:
int x;
int y;
mutable int z;
int sum;
};
const修饰的函数返回值:
值返回,修饰值返回函数没有任何意义
const int geta()
{
return 10;
}
const int b3 = geta();
int a3 = geta();
cout << “b3=” << b3 << " a3=" << a3 << endl;
返回值带不带const都可以使用。

指针返回

const int *getponit()
{
int *a = new int[10];
for (int i = 0; i < 10; i++)
{
a[i] = i;
}
return a;
}
const int *pp1 = getponit();
for (int i = 0; i < 10; i++)
{
cout << pp1[i] << endl;
}
//int *pp2 = getponit();//无法从const int 转换为int。不允许非const指针接受const函数返回的指针。
我们写代码要多用const,这样可以利用编译器来把我们处理一些问题,提高我们代码的健壮性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值