歡迎您光臨本站 註冊首頁

C++中const的特性的使用

←手機掃碼閱讀     zmcjlove @ 2020-05-08 , reply:0

目錄(作用):
1:修飾變量,說明該變量不可以被改變;
2:修飾指針,分為只想常量的指針和自身是常量的指針
3:修飾引用,指向常量的引用,用於修飾形參,即避免了拷貝,有避免了函數對值的修改;
4:修改成員函數:說明該成員函數內不能修改成員變量。
5:指針與引用
正文:
以下是對各種情況的示例:
//注:1:const修飾的引用cj的值且引用的對象無法修改無法修改,但是引用的i是可修改的 #include

using namespace std; int main() { int i = 1; const int &cj = i; cout << "cj : " <<cj<< endl;(√) i=2; cout << "cj : " <<cj<< endl;(√) cj=3; cout << "cj : " <<cj<< endl;(×) int a=9; cj=a; (×) return 0; } 錯誤提示: /code/main.cpp: In function ‘int main()': /code/main.cpp:15:4: error: assignment of read-only reference ‘cj' cj=3; ^ /code/main.cpp:19:4: error: assignment of read-only reference ‘cj' cj=a; ^ sandbox>exited with status 0
//注:常量引用,本身也要是常量才行: #includeusing namespace std; int main() { const int i = 4; const int &ck = i; //正確,常量對象綁定到 const引用 cout<< "ck="<<ck<<endl; const int b = 5; int &r = b; //錯誤, return 0; } /code/main.cpp: In function ‘int main()': /code/main.cpp:13:14: error: invalid initialization of reference of type ‘int&' from expression of type ‘const int' int &r = b; //錯誤, ^ sandbox>exited with status 0
//注:const 的隱式轉換: #includeusing namespace std; int main() { double b = 2.14; const int &a = b; // 會進行如下轉換: // int temp = b; // const int &a=temp; // 所以,給b進行賦值,a可能 cout<<"a="<<a<exited with status 0
//注:修飾成員函數_1: class Date { private: int m_year; int m_month; int m_day; public: int GetDay(void) const { m_day=7; return m_day;//修飾的情況下,不能對成員變量進行修改; } }; // void GetDay(void) const // { // return m_day; // } int main() { double b = 2.14; const int &a = b; // 會進行如下轉換: // int temp = b; // const int &a=temp; // 所以,給b進行賦值,a可能 cout<<"a="<<a<exited with status 0
//注:修飾函數_2 #includeusing namespace std; class Date { private: int m_year; int m_month; mutable int m_day;//通過被mutable修改的成員變量,就可以被修改了 public: int GetDay(void) const { m_day=7; return m_day; } }; // void GetDay(void) const // { // return m_day; // } int main() { double b = 2.14; const int &a = b; // 會進行如下轉換: // int temp = b; // const int &a=temp; // 所以,給b進行賦值,a可能 cout<<"a="<<a<exited with status 0
//注:const修飾的指針 #includeusing namespace std; int main() { const int* p = NULL;//這兩種修飾的是*p指向的值 //int const* p = NULL; int a=9; p=&a;//修改了p指向的地址,任然沒有出錯 cout<<"*p="<<*p<<endl<<"p="<<p<<endl; int c=10; int* const b = &c;//這兩種修飾的是p指向的地址 c=45; *b=c;//修改了b指向的值,任然不會出錯 cout<<"*b="<<*b<<endl<<"b="<<b<<endl; b=&a;//這裡有問題了,b指向的地址是不能修改的 cout<<"*b="<<*b<<endl<<"b="<<b<exited with status 0

//注:const修飾的引用 #includeusing 

namespace std;

 int main() {

 int x = 3; 

const int& y = x; 

cout<<"y="<<y<<endl; 

x=9; cout<<"y="<<y<<endl; 

y=9;

//const修飾的引用是不能夠在更改引用指向的對象的 

cout<<"y="<<y<exited with status 0



[zmcjlove ] C++中const的特性的使用已經有304次圍觀

http://coctec.com/docs/c/language/show-post-233291.html