zoukankan      html  css  js  c++  java
  • Const详解2

    8.3 传递和返回地址

      事实上,无论什么时候传递一个地址给一个函数,都应该尽可能用const修饰它。如果不这么样做,就不能以const指针参数的方式使用这个函数。

      看下面的例子:

    // const_reference.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    void t(int*)
    {
    }
    
    void u(const int* cip)
    {
        //*cip = 2;    *cip can't be modified
        int i = *cip;
        //int* ip2 = cip; non-const
    }
    const char* v()
    {
        return "result of function v()";
    }
    
    const int* const w()
    {
        static int i;
        return &i;
    }
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int x = 0;
        int* ip = &x;
        const int* cip = &x;
        t(ip);
        // t(cip); can't be const int*
        u(ip);
        u(cip);
        //char* cp = v(); return const char*
        const char* ccp = v();
        //int* ip2 =w();  return const int*
        const int* const ccip = w();
        const int* cip2 = w();
        //*w() = 1; *w() is const, can't be modified
    
        return 0;
    }

    2、static const
         static 无论一个类被创建多少次,都只有一个实例。

      类中的一个常量成员,在该类中的所有对象中它都是一样的。因此,一个内部类型的static const 可以看做一个编译期间的常量。

      注意:必须在static const 定义的地方对它进行初始化。

  • 相关阅读:
    检查c# 内存泄漏
    条件请求与区间请求
    python排序算法
    webpack+react+redux+es6
    Wireshark命令行工具tshark
    Web的形式发布静态文件
    PyQT制作视频播放器
    DotNet二维码操作组件ThoughtWorks.QRCode
    给你讲个笑话,我是创业公司CEO
    分库分表总结
  • 原文地址:https://www.cnblogs.com/wiessharling/p/2985250.html
Copyright © 2011-2022 走看看