zl程序教程

您现在的位置是:首页 >  其它

当前栏目

使用 const 提高函数的健壮性

函数 提高 const 使用
2023-09-14 09:12:04 时间

使用 const  提高函数的健壮性

看到 const 关键字,C++程序员首先想到的可能是 const 常量。这可不是良好的条件 反射。如果只知道用 const 定义常量,那么相当于把火药仅用于制作鞭炮。const 更大的 魅力是它可以修饰函数的参数、返回值,甚至函数的定义体。

const 是 constant 的缩写, “恒定不变”的意思。被 const 修饰的东西都受到强制保护, 可以预防意外的变动,能提高程序的健壮性。所以很多 C++程序设计书籍建议:“Use const whenever you need”。

 

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 //定义f()函数
 6 f(int x,int y)     //f()的参数以值方式传递
 7 {
 8     ++x;
 9     --y;
10     cout<<"x="<<x<<",y="<<y<<endl;
11 }
12 int main(int argc, char** argv) {
13         int a,b;
14 
15     //设置实际参数的值
16     a=b=10;
17     //以变量为参数调用f()函数
18     f(a,b);
19 
20     //验证实际参数的值
21     cout<<"a="<<a<<",b="<<b<<endl;
22 
23     //以表达式参数形式调用f()函数
24     f(2*a,a+b);
25     return 0;
26 }