变量声明和变量是有区别的
extern int i; //只是声明i而非定义i int j; //声明而且还定义了j
任何一个显式初始化的声明都将成为定义,而不管有没有extern,extern语句一旦变量赋予了初始值就变成了定义。
extern double pi=3.1415926; //定义
state.cpp
#include "stdafx.h" #include "state.h"/*1.如果变量放在state.h头文件,则无法被外部文件使用extern关键字使用2.如果cpp文件和h文件都包含相同的变量,则外部文件使用extern关键字时,无法获得该变量的值 */ int x; state::state() {x = 10; }state::~state() { }
C++Starter.cpp
// C++Starter.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "iostream" #include <ctime> #include "state.h" using namespace std;extern int x; int main() {state aa; //如果不初始化state类,则变量x的值为0cout << "x=" << x << endl;return 0; }