C++ const

来源:互联网 发布:怎样安装photoshop软件 编辑:程序博客网 时间:2024/04/29 13:49

1. 在C++中const对象默认为文件的局部变量(作用域是文件局部变量),通过指定const变量为extern,就可以在整个程序中访问const变量


未添加extern,以下程序链接出错

//var.cppconst int MAX = 100;

//var.hextern int MAX;

#include <iostream>using namespace std;#include "var.h"int main(){    int x = MAX;    cout << "x = " << x << endl;    return 0;}

error:

g++ -o main main.cpp var.cpp
/tmp/cc2YqVv9.o: In function `main':
main.cpp:(.text+0xa): undefined reference to `MAX'
collect2: ld returned 1 exit status
make: *** [main] Error 1


添加extern,以下程序编译OK

//var.cppextern const int MAX = 100;

//var.hextern int MAX;

#include <iostream>using namespace std;#include "var.h"int main(){    int x = MAX;    cout << "x = " << x << endl;    return 0;}





0 0
原创粉丝点击