[C++基础]013_神奇的const

[C++基础]013_神奇的const

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不能被修改。

 
posted @ 2013-03-18 13:03  小薇林  阅读(170)  评论(0编辑  收藏  举报