更多课程 选择中心

C/C++培训
达内IT学院

400-111-8989

C++中的不同文件中相同变量的共享细节问题

  • 发布:C++培训
  • 来源:学习笔记
  • 时间:2017-07-05 16:30

使用extern实现变量共享

在此之前,先来看这样一行代码

//text1.h

 //extern int bufsize;我这里先把头文件中的东西注释掉,方便比较不同。

//text2.cpp

#include"text1.h"

#include<iostream>

using namespace std;

 int fun()

 {

int bufsize = 44;//注意这里重新定义了bufsize

cout << bufsize;

return 0;

}

//text1.cpp

#include<iostream>

#include"text1.h"

using namespace std;

int bufsize = 12;

 void main()

{

int fun();                

cout << fun();

cout << bufsize;

}

这里的结果非常明显,输出的是44012.

好,那么再来看下面的代码。

//text1.h

 extern int bufsize;

//text2.cpp

#include"text1.h"

#include<iostream>

using namespace std;

 int fun()

 {

int bufsize = 44;//注意这里

cout << bufsize;

return 0;

}

//text1.cpp

#include<iostream>

#include"text1.h"

using namespace std;

int bufsize = 12;

 void main()

{

int fun();

cout << fun();

cout << bufsize;

}

我关掉了头文件中的注释,结果是一样的,好吧,是一样的没错,看了作用域的可以无视上面的了。

再看下面的代码

//text1.h

 extern int bufsize;

//text2.cpp

#include"text1.h"

#include<iostream>

using namespace std;

 int fun()

 {

 bufsize = 44;//注意这里,把int去了,就不是重新声明并定义了,而是给共享的bufsize赋值了。

cout << bufsize;

return 0;

}

//text1.cpp

#include<iostream>

#include"text1.h"

using namespace std;

int bufsize = 12;

 void main()

{

 int fun();

cout << fun();

cout << bufsize;

}

结果当然是44044了,因为在主函数中先调用了fun函数,bufsize被重新赋值为44,然后返回一个0,因为bufsize实现共享,所以主函数中的bufsize变成了44了。

当然还有些更简单的方式能实现这个功能,这里只是写了extern的一些笔记和感想。

预约申请免费试听课

填写下面表单即可预约申请免费试听!怕钱不够?可就业挣钱后再付学费! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:C++语言学习书籍推荐,C++编程进阶书籍
下一篇:初学C++需要掌握哪些知识点?

C语言创建windows窗口实例

C++回调函数是什么?

C++ shared_ptr和动态数组

C语言有哪些关键词,C语言44个关键词大全

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

  • 搜索抖音号

    搜索抖音号:1821685962

    免费领取达内课程视频学习资料

Copyright © 2021 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省