zoukankan      html  css  js  c++  java
  • C++ const 的其它用法

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

      const 是 constant 的缩写,“恒定不变”的意思。被 const 修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。

    1.用const修饰函数的参数

      如果参数作输出用,不论它是什么数据类型,也不论它采用“指针传递”还是“引用传递”,都不能加 const 修饰,否则该参数将失去输出功能。
      const 只能修饰输入参数:  
    如果输入参数采用“指针传递”,那么加 const 修饰可以防止意外地改动该指针,起到保护作用。 例如 StringCopy 函数:
              void StringCopy(char *strDestination, const char *strSource);
    其中 strSource 是输入参数,strDestination 是输出参数。给 strSource 加上 const 修饰后,如果函数体内的语句试图改动 strSource 的内容,编译器将指出错误。

    2.用 const 修饰函数的返回值

     如果给以“指针传递”方式的函数返回值加 const 修饰,那么函数返回值(即指针)的内容不能被修改,该返回值只能被赋给加 const 修饰的同类型指针。 例如函数
              const char * GetString(void);
    如下语句将出现编译错误:
              char *str = GetString();
    正确的用法是
              const char *str = GetString();

      

  • 相关阅读:
    浅析椭圆曲线加密算法(ECC)
    比特币原理——交易与UTXO
    比特币白皮书-学习笔记
    python SMTP邮件发送
    Linux : Forks()
    IS: [=Burp Suite No.4=]Burp Suite /Scanner/ and /Intruder/
    IS: [=Burp Suite No.3=]Burp Suite /Target/ and /Spider/
    IS: [=Burp Suite No.2=]Burp Suite SSL and advanced options
    IS: [=Burp Suite No.1=]Burp Suite install and configuration
    IS: WMIC command use
  • 原文地址:https://www.cnblogs.com/zxwAAA/p/3002965.html
Copyright © 2011-2022 走看看