const這個關鍵字大家肯定都很熟悉,它的意思就是,被我修飾(保護)的東西,你不能改,下面來研究一下它!
1. 常量
1 int main(){2 const int value = 1;3 value = 2;4 return 0;5 }
上面的代碼是會報錯的,被const修飾的value是無法修改的。
2. 常成員函數
1 class Test{ 2 public: 3 void test() const{ 4 i = 1; 5 j = 2; 6 } 7 private: 8 int i; 9 int j;10 };
上面的代碼是會報錯的,常成員函數是不能修改類的成員變數的。
3. 常對象和常成員函數
1 #include <iostream> 2 using namespace std; 3 4 class Test{ 5 public: 6 void test() const{ 7 cout<<"const function"<<endl; 8 } 9 void test1(){10 cout<<"test1 function"<<endl;11 }12 private:13 int i;14 int j;15 };16 17 18 int main(){19 const Test t;20 t.test();21 t.test1();22 23 return 0;24 }
上面的代碼是會報錯的,t.test1();這段代碼報的錯,因為test1()不是個常成員函數,所以會報錯!-------常對象只能調用其常成員函數。
4. 常量形參
1 #include <iostream> 2 using namespace std; 3 4 int testFunc(const int& value){ 5 value = 12; 6 return value; 7 } 8 9 int main(){10 int value = 1;11 testFunc(value);12 return 0;13 }
上面的代碼是會報錯的,因為testFunc()的形參是const的,無法修改。
5. 其他常
1 class Test{2 public:3 const void test(){ 4 cout<<"const function"<<endl;5 }6 private:7 int i;8 int j;9 };
上面的代碼在test()前加了const,實際上這樣是毫無效果的,即使void是int也沒有用,這種定義就是閑的蛋疼。
1 #include <iostream> 2 using namespace std; 3 4 class Test{ 5 public: 6 Test(){ 7 instance = new Test(); 8 } 9 const Test& test(){ 10 cout<<"const function"<<endl;11 return *instance;12 }13 private:14 Test *instance;15 };16 17 int main(){18 19 return 0;20 }
上面的代碼就有意義了,返回的instance不能被修改。