c++ 全局变量 测试 static extern

今天,来整理下,全局变量的一些用法:

先说static : 我们建立一个工程,命名为mytext,然后建立一个头文件 global.h,  在创建一个myfirst的类。

myfirst.h 文件为:

#pragma once
#include <iostream>

using namespace  std;
class myfirst
{
public:
	myfirst();
	~myfirst();
};

 global.h 头文件为:

#include "myfirst.h"


class  ABC
{
public:
	static int oneNum;
	static myfirst thcar;
	
};

  global.cpp

#include "stdafx.h"
#include "global.h"

//myfirst thcar;

myfirst ABC::thcar;
int  ABC::oneNum = 10;

myfirst.cpp

#include "stdafx.h"
#include "myfirst.h"
#include "global.h"

//int ABC::oneNum = 3;

myfirst::myfirst()
{
//    ABC::oneNum  = 2;
	cout << 1 << endl;
	cout << ABC::oneNum << endl;
}


myfirst::~myfirst()
{
	cout << -1 << endl;
}

对应的主函数部分为:

#include "stdafx.h"

#include "global.h"


int main()
{
	
//	int  ABC::oneNum  = 10;
	ABC::oneNum = 5;
	int abc = 0;
	cout << ABC::oneNum << endl;
//	getchar();
    return 0;
}

 这样运行结果为:

        可以看出,先初始化类,执行构建函数,调用全局ABC:: oneNum ,然后执行主函数中,对变量的改变。这样在其他cpp 内容,调用的是一个变量,也许有人问了,为什么要在类中定义静态变量,直接定义不好么,如果你在一个头文件中直接定义一个static 类型的变量,你在其他cpp文件中,添加这个头文件的话,它的范围是对应每个cpp文件的范围,每个cpp范围都都会新定义一个新的static 变量,也就是说多个cpp文件调用的并不是同一个变量。(自己可以试试呦)

       extern 用法就比较简单:

  global.h

extern myfirst thcar;

   global.cpp

 myfirst thcar

  这样别的cpp文件包含此头文件,调用的就是全局变量了。

发布了40 篇原创文章 · 获赞 13 · 访问量 5885

猜你喜欢

转载自blog.csdn.net/weixin_42126427/article/details/104723205
今日推荐