使用extern关键字在头文件/ c ++中声明变量 [英] using extern keyword to declare variables in header files / c++

查看:229
本文介绍了使用extern关键字在头文件/ c ++中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++头文件中声明变量的正确方法是什么?如果这不是一个好主意,那为什么?谢谢。

解决方案

正确的方法是在头文件中用extern关键字声明变量,然后必须在一个(!)cpp文件中声明它,而不使用extern关键字。

头文件中的变量是全局变量。这些问题很多。这里有一些:


  • 你不知道它们按什么顺序被初始化。当一个类是一个类,并且它的构造函数访问另一个全局变量时,可能这个其他全局变量没有被初始化

  • 全局变量浪费你的名字空间
  • 当你使用全局变量时,你几乎肯定不会使用众所周知的和经过验证的编程概念(比如模块化)。你的功能也会有很多副作用,这会让你的代码难以理解。在几个星期之内,你将不再知道,哪些函数会改变哪些变量,等等。如果你坚持这个概念并且不使用全局变量,你的代码将更加可读和易于理解。
  • 在C ++中使用全局变量。他们只是为了向后兼容C。


    What is the proper way of declaring variables in the header file in c++? And if it is not a good idea, then why? Thank you.

    解决方案

    The correct way would be to declare the variable with the extern keyword in the header file and then you have to declare it in one (!) cpp file without the extern keyword.

    But:

    Variables in header files are global variables. These have much problems. Here a few:

    • You don't know in which order they are initialized. When one is a class and their constructor accesses another global variable, it is possible that this other global variable isn't initialized
    • Global variables waste your namespace
    • When you use global variables, you almost certainly don't use well-known and proven programming concepts (like modularity). Also your functions will have many side effects which makes your code hard to understand. In a few weeks you will no longer know, which functions will change which variables, and so on. Your code will be much more readable and understandable, if you stick to this concepts and don't use global variables.

    You should never use global variables in C++. They are only there for backward compatibility with C.

    这篇关于使用extern关键字在头文件/ c ++中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆