设为首页 加入收藏

TOP

C++ const用法小结 (欢迎大家拍砖)(二)
2015-07-24 06:37:33 来源: 作者: 【 】 浏览:51
Tags:const 用法 小结 欢迎 大家
urn _cm;
20?
21 ? ? }
22?
23 private:
24?
25 ? ? int _cm;
26?
27 };
28?
29 ?
30?
31 void Cmf(const Test& _tt)
32?
33 {
34?
35 ? ? cout<<_tt.get_cm();
36?
37 }
38?
39 int main(void)
40?
41 {
42?
43 ? ? Test t(8);
44?
45 ? ? Cmf(t);
46?
47 ? ? system("pause");
48?
49 ? ? return 0;
50?
51 }
复制代码
//结果输出 8
?
?
?
对于const修饰函数的返回值
?
Const修饰返回值分三种情况。
?
A:const修饰内置类型的返回值,修饰与不修饰返回值作用一样。
?
复制代码
?1 #include
?2?
?3 using namespace std;
?4?
?5 const int Cmf()
?6?
?7 {
?8?
?9 ? ? return 1;
10?
11 }
12?
13 int Cpf()
14?
15 {
16?
17 ? ? return 0;
18?
19 }
20?
21 int main(void)
22?
23 {
24?
25 ? ? int _m = Cmf();
26?
27 ? ? int _n = Cpf();
28?
29 ?
30?
31 ? ? cout<<_m<<" "<<_n;
32?
33 ? ? system("pause");
34?
35 ? ? return 0;
36?
37 }
?
?
?
B:const 修饰自定义类型的作为返回值,此时返回的值不能作为左值使用,既不能被赋值,也不能被修改。
?
?
?
C: const 修饰返回的指针或者引用,是否返回一个指向const的指针,取决于我们想让用户干什么。
?
?
?
?
?
四、const修饰类成员函数.
?
const 修饰类成员函数,其目的是防止成员函数修改被调用对象的值,如果我们不想修改一个调用对象的值,所有的成员函数都应当声明为const成员函数。注意:const关键字不能与static关键字同时使用,因为static关键字修饰静态成员函数,静态成员函数不含有this指针,即不能实例化,const成员函数必须具体到某一实例。
?
?
?
下面的get_cm()const;函数用到了const成员函数
?
?
?
复制代码
?1 #include
?2?
?3 using namespace std;
?4?
?5 class Test
?6?
?7 {
?8?
?9 public:
10?
11 ? ? Test(){}
12?
13 ? ? Test(int _m):_cm(_m){}
14?
15 ? ? int get_cm()const
16?
17 ? ? {
18?
19 ? ? ? ?return _cm;
20?
21 ? ? }
22?
23 private:
24?
25 ? ? int _cm;
26?
27 };
28?
29 ?
30?
31 void Cmf(const Test& _tt)
32?
33 {
34?
35 ? ? cout<<_tt.get_cm();
36?
37 }
38?
39 int main(void)
40?
41 {
42?
43 ? ? Test t(8);
44?
45 ? ? Cmf(t);
46?
47 ? ? system("pause");
48?
49 ? ? return 0;
50?
51 }
复制代码
?
?
如果get_cm()去掉const修饰,则Cmf传递的const _tt即使没有改变对象的值,编译器也认为函数会改变对象的值,所以我们尽量按照要求将所有的不需要改变对象内容的函数都作为const成员函数。
?
?
?
?如果有个成员函数想修改对象中的某一个成员怎么办?这时我们可以使用mutable关键字修饰这个成员,mutable的意思也是易变的,容易改变的意思,被mutable关键字修饰的成员可以处于不断变化中,如下面的例子。
?
?
?
复制代码
?1 #include
?2 using namespace std;
?3 class Test
?4 {
?5 public:
?6 ? ? Test(int _m,int _t):_cm(_m),_ct(_t){}
?7 ? ? void Kf()const
?8 ? ? {
?9 ? ? ? ? ++_cm; //it's wrong
10 ? ? ? ? ++_ct; //it's right
11 ? ? }
12 private:
13 ? ? int _cm;
14 ? ? mutable int _ct;
15 };
16?
17 int main(void)
18 {
19 ? ? Test t(8,7);
20 ? ? return 0;
21 }
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ - 1324 Holedox Moving 下一篇HUNNU Contest 跑得快计数程序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: