类中的静态成员变量和C++中的全局变量有什么区别?

what is the difference between static memeber variable in a class and global variable in C++?

本文关键字:什么 全局变量 区别 静态成员 变量 C++      更新时间:2023-10-16

类中的静态成员变量和C++中的全局变量有什么区别?

我可以通过类名(类名::静态变量)访问程序中任何地方的类中的静态成员变量,因此在创建变量时如何确定变量是类和全局变量中的静态成员变量?

主要区别在于范围。

静态成员变量位于类的范围内,如果要访问它,则必须使用类范围限定作为名称。像类名称::变量名称。这可以防止命名空间污染。因此,它不能与其他变量混淆。

全局变量在全局范围内,可以从任何地方访问(如果我们有外部声明或内联定义):如果我们在内部范围内,我们可以使用 :: 运算符来选择范围。

还有命名空间。如果在类或函数之外的命名空间中定义变量,则它属于命名空间。要访问它,您需要使用完全限定的名称:::命名空间Name::variableName。对于嵌套命名空间,您需要添加更多 ::

请参阅示例:

#include <iostream>
#include <string>
std::string variable{"global scopen"};
namespace test{
std::string variable{"namespace scopen"};
struct TestStruct {
std::string variable{"class scopen"};
void function()
{
std::string variable{"function scopen"};
std::cout << variable << 'n' << this->variable << 'n' << ::test::variable << 'n' << ::variable << 'n';
}
};
}
int main()
{
test::TestStruct t;
t.function();
return 0;
}

但需要注意。您需要知道,如果定义静态类成员,则对于该类的所有实例都是通用的。因为实际上它是一个全局变量,只是在类的作用域中定义。