为了账号安全,请及时绑定邮箱和手机立即绑定

C++中const的特性

标签:
AngularJS

目录(作用):

1:修饰变量,说明该变量不可以被改变;

2:修饰指针,分为只想常量的指针和自身是常量的指针

3:修饰引用,指向常量的引用,用于修饰形参,即避免了拷贝,有避免了函数对值的修改;

4:修改成员函数:说明该成员函数内不能修改成员变量。

5:指针与引用

正文:

以下是对各种情况的示例:

注:1:const修饰的引用cj的值且引用的对象无法修改无法修改,但是引用的i是可修改的 1 #include 2 3 using namespace std; 4 5 int main() { 6 int i=1; 7 const int &cj=i; 8 9 cout << "cj : " < exited with status 035

1 注:常量引用,本身也要是常量才行: 2 3 #include 4 5 using namespace std; 6 7 int main() { 8 const int i=4; 9 10 const int &ck=i; //正确,常量对象绑定到 const引用11 cout<< “ck=”< exited with status 0

1 注:const 的隐式转换: 2 3 #include 4 5 using namespace std; 6 7 int main() { 8 double b=2.14; 9 const int &a=b;10 // 会进行如下转换:11 // int temp=b;12 // const int &a=temp;13 // 所以,古玩给b进行赋值,a可能14 cout<<“a=”< exited with status 0

1 注:修饰成员函数_1: 2 3 class Date 4 { 5 private: 6 int m_year; 7 int m_month; 8 int m_day; 9 public:10 int GetDay(void) const11 {12 m_day=7;13 return m_day;//修饰的情况下,不能对成员变量进行修改;14 }15 };16 17 // void GetDay(void) const18 // {19 // return m_day;20 21 // }22 23 int main() {24 double b = 2.14;25 const int &a = b;26 // 会进行如下转换:27 // int temp = b;28 // const int &a=temp;29 // 所以,给b进行赋值,a可能30 cout<<“a=”< exited with status 0

1 注:修饰函数_2 2 3 #include 4 5 using namespace std; 6 7 8 9 class Date10 {11 private:12 int m_year;13 int m_month;14 mutable int m_day;//通过被mutable修改的成员变量,就可以被修改了15 public:16 int GetDay(void) const17 {18 m_day=7;19 return m_day;20 }21 };22 23 // void GetDay(void) const24 // {25 // return m_day;26 27 // }28 29 int main() {30 double b=2.14;31 const int &a=b;32 // 会进行如下转换:33 // int temp=b;34 // const int &a=temp;35 // 所以,给b进行赋值,a可能36 cout<<“a=”< exited with status 0

1 注:const修饰的指针 2 3 4 #include 5 6 using namespace std; 7 8 9 int main() {10 const int* p=NULL;//这两种修饰的是p指向的值11 //int const p=NULL;12 13 int a=9;14 p=&a;//修改了p指向的地址,任然没有出错15 cout<<"*p="<<*p<

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消