C++ - extern const的问题
来源:互联网 发布:软件测试绩效考核 编辑:程序博客网 时间:2024/06/18 06:34
原文地址:http://blog.sina.com.cn/s/blog_76fbd24d0101a62k.html
1. 具体问题场景:
需要在A.cpp中定义一个const常量,并在B.cpp中引用这个常量,出错的场景:
// A.cpp
const int NUM = 100;
// B.cpp
extern const int NUM;
// 编译错误,错误提示外部符号NUM无法解析,未定义。
2. 出错原因:
const对象默认为文件的局部变量。
3. 关于非const:
在全局作用域里定义非const变量时,它在整个程序中都可以访问。可以把一个非const变量定义在一个文件中,并在另外的文件中使用这个变量:
// A.cpp
int counter; // 定义非const变量counter
// B.cpp
extern int counter; // 对A.cpp中的非const变量counter进行声明引用
++counter; // 使用非const变量counter
4. 关于const:
在全局作用域声明的const变量是定义在该对象的文件的局部变量。此变量只存在于那个文件中,不能被其他文件访问。通过显式地指定const变量为extern,就可以在整个程序中访问const对象。
// A.cpp
extern const int NUM = 100;
// B.cpp
extern const int NUM;
for (i = 0; i < NUM; i++)
// 注意:B.cpp中的NUM也是extern,但是这个extern标志着NUM是一个声明,所以没有初始化式。
5. 列举几种情形的对与错:
(1)ERROR: B.cpp中的NUM无法解析,未定义。
// A.cpp
const int NUM = 100;
// B.cpp
extern const int NUM;
int i = NUM;
(2)OK
// A.cpp
const int NUM = 100;
// B.cpp
extern const int NUM = 99;
int i = NUM;
(3)OK
// A.cpp
extern const int NUM = 100;
// B.cpp
extern const int NUM;
int i = NUM;
(4)ERROR: NUM重定义
// A.cpp
extern const int NUM = 100;
// B.cpp
extern const int NUM = 99;
int i = NUM;
(5)OK
// A.cpp
extern const int NUM = 100;
// B.cpp
const int NUM = 99;
int i = NUM;
(6)OK
// A.cpp
const int NUM = 100;
// B.cpp
extern const int NUM = 99;
int i = NUM;
6. 几种声明使用常量的方法:
(1)在一个.cpp文件中使用extern定义const常量,在使用的地方extern声明引用。
(2)全部在头文件中进行const定义,在使用的地方包含头文件,但不要使用extern,否则多个包含此头文件的.cpp文件将出现重定义错误。
(3)在一个.cpp文件中extern定义,在头文件中extern声明,在使用的地方包含头文件(适用于大量常量情形)。
(4)避免常量,使用函数:
double PI()
{
}
- C++ - extern const的问题
- C++ - extern const的问题
- extern “C”的问题
- extern const PixFmtInfo pix_fmt_info[] 的链接问题
- extern 和extern “C"的问题
- 古典问题、extern、const
- 关于 extern "C" 的问题
- 关于extern "C" 的问题
- extern "C"的问题研究
- extern "c"的使用问题
- extern const的烦恼
- extern “C” const __declspec(selectany)
- C-static,const,volatile,extern
- C----extern,static,typedef,const
- c/c++ static extern const
- C语言中const,extern,static,volatile的使用
- Object C语法中const、extern和static的含义
- C语言中Valtile,Const,extern的解释
- WIFI射频芯片+8M mcu
- 中国IC概况
- linux下运行后台程序——nohup
- SQL SERVER 2008自动备份图解教程
- eclipse启动参数设置大全
- C++ - extern const的问题
- wpa_supplicant无线网络配置
- 浮华落寂
- Frame和Bounds的区别,图示,一目了然,一清二楚,一针见血
- lazy value可以在需要的时候重新计算值,但不是重新赋值。
- 如何重写flex控件
- php-fpm占用cpu100%的奇怪原因
- 不要重载全局 ::operator new()
- HBA卡