类中的静态和全局变量 [英] static and global variable inside a class

查看:135
本文介绍了类中的静态和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来看一个班级说 CMyClass 。里面 CMyClass.cpp 是一个定义的全局变量。

并且可能也用在其他地方。我很好奇在类中有这个全局变量的意义是什么时候还可以在其中声明一个静态成员变量? (有什么区别?他们都喜欢类范围吗?(按类范围我的意思是什么对静态变量有效,例如,通过所有类对象的一个​​实例)。)

解决方案

不能在类中有一个全局变量(类中的所有变量都是类成员)。

通常使用类静态变量而不是全局变量(例如,参见什么是使用全局变量的良好编码标准? [ ^ ])。

I came to see one class say CMyClass. There inside CMyClass.cpp is a global variable defined.
And probably also used somewhere else. I was curious what is the point of having this global variable inside class when one could also declare say a static member variable inside it? (what''s the difference? they both enjoy class scope right? (by class scope I mean what is valid with static variables, e.g., one instance through all class objects) ).

解决方案

You cannot have a global variable inside a class (all the variables inside the class are class members).
Class static variables are often used instead of global variables (see, for instance, "What''s a good coding standard for using global variables?"[^]).


这篇关于类中的静态和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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