我对 static
/global
/global static
/extern
变量的用法有点困惑。
我希望在创建类实例时增加一个计数器变量。
如果有人可以发布对每个适当用法的说明,将不胜感激。
最佳答案
根据面向对象的概念,您应该永远使用全局静态
变量。
您可以在 class
中为 class
的实例计数定义一个 static
变量。
将其设置为 private
,这样除了您的构造函数之外没有其他人可以增加计数。
提供一个 public
函数来获取计数器。请参见下面的示例:
你的类.h:
class YourClass {
private:
static int instanceCount_;
public:
YourClass() {++YourClass::instanceCount_;} // constructor
~YourClass() {--YourClass::instanceCount_;} // destructor
static int instanceCount() {return instanceCount_;}
};
你的类.cpp:
int YourClass::instanceCount_ = 0;
就static
/global
/global static
/extern
的概念而言
静态
:
1a) 全局静态
:
按给定方式创建的静态变量:static int numberOfPersons;
这种变量只能在一个文件中看到(不会与其他文件中的同名变量发生名称冲突)
1b) class static
: (在上面的实例计数中已经有一个例子)
一个类可能有 static
成员,这些成员对该类可见(只能通过 Class::VarName
语法访问)(而不是上面所说的“仅文件”)。它不会与其他类中的同名变量发生名称冲突。每个类(不是每个实例)只有一个拷贝。
1c) global static
和 class static
都是global
(因为它们可以全局访问,或者使用类限定符 Class::
或不。
所以,1a., 1b.和 1c。部分解释static
、global
和global static
- 全局变量的另一种形式,就是定义一个没有
static
的变量 语法:int numberOfPersons;
没有static
,这个变量可以被其他文件看到,使用extern
关键字。并且它会与其他文件中具有相同名称的变量发生名称冲突。因此,在全局范围内,您只能在所有源文件中定义它一次。
extern
:声明在其他地方定义的变量/函数。它通常出现在头文件中。我们可以在其他文件中定义一些变量,并在使用它的另一个源文件中将此变量声明为extern
,如下所示。
extern int numberOfPersons;
int addPersonCount()
{
numberOfPersons++;
}
希望这对您有所帮助。
关于c++ - 何时使用静态变量 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25866893/