zoukankan      html  css  js  c++  java
  • const常量用extern声明定义的问题(extern变量不能在使用类里初始化)

    test.h

    [cpp] view plain copy
     
    1. #ifndef TEST_H_  
    2. #define TEST_H  
    3.   
    4. //常量声明和定义采取这种方法即可  
    5. const int a = 20;  //不报错,因为const变量链接属性默认是内部链接,就算两个cpp文件都引用了该.h文件,也不会出现重复定义的错误。  
    6.   
    7. //extern const int b = 20;//这个报错,因为加上extern之后链接属性就是外部链接了,当被多个.cpp文件包含时则会导致重定义。  
    8.   
    9. extern const int  b;    //改成这个不报错,所以用extern只声明变量,而在test.cpp定义这个变量  
    10.   
    11. #endif  

    test.cpp

    [cpp] view plain copy
     
    1. #include "test.h"  
    2.   
    3. const int b = 3;//定义b,如果只在test.h里用extern声明了,而没有定义,那么因为在main.cpp使用了变量b,就会出现链接错误  

    main.cpp

    [cpp] view plain copy
     
    1. #include "test.h"  
    2. #include <iostream>  
    3. using namespace std;  
    4.   
    5. int main()  
    6. {  
    7.     cout << b << endl;  
    8.   
    9.     return 0;  
    10. }  

    http://blog.csdn.net/bladeandmaster88/article/details/64906841

  • 相关阅读:
    Consul注销实例
    sql优化基础篇
    linux下执行java类(运行java定时器)
    ExecutorService 的理解与使用
    精度计算的方法
    内部类详解
    接口的作用
    面向对象之继承和组合浅谈
    构造器前篇
    教师编制考试数据分析
  • 原文地址:https://www.cnblogs.com/findumars/p/8436805.html
Copyright © 2011-2022 走看看