zoukankan      html  css  js  c++  java
  • 使用 const 提高函数的健壮性

    使用 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 }
  • 相关阅读:
    Google搜索引擎如何运作:不会手动调整结果
    一个Ruby脚本
    IE灭绝!?
    除Windows之外的其他操作系统
    刚收到的新书
    奇怪的计算机语言
    小巧的menuetOS
    Ruby学习笔记(1)
    一个通知
    总结 asp.net 和 javascript获取本地IP(MAC)和服务器IP(MAC)的方法
  • 原文地址:https://www.cnblogs.com/borter/p/9406575.html
Copyright © 2011-2022 走看看