码迷,mamicode.com
首页 > 编程语言 > 详细

C++常函数

时间:2014-08-01 10:42:21      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   2014   代码   

常函数即在类的成员函数参数列表后放置const的函数,常函数的作用是限制函数体对成员变量的修改,此外,常函数也不能调用非 常函数。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Test
 5 {
 6 private:
 7     int x, y;
 8 public:
 9     Test() { x = 0; y = 0;}
10     void changeValue() const 
11     { 
12         x = 7; 
13         y = 7; 
14         print();
15     }
16     void print() { cout << x << endl << y << endl; }
17 };
18 
19 int main()
20 {
21     Test t;
22     t.changeValue();
23     //t.print();
24     return 0;
25 }

编译错误结果为:bubuko.com,布布扣

其实,在代码当中如果我们确定某成员函数不会修改成员变量,就应该将其定义为常函数,这样如果不小心写错代码修改了变量的值就会编译不过。提高代码的健壮性。

C++常函数,布布扣,bubuko.com

C++常函数

标签:style   blog   http   color   os   io   2014   代码   

原文地址:http://www.cnblogs.com/lit10050528/p/3884283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!