类中的静态成员变量和C++中的全局变量有什么区别?
what is the difference between static memeber variable in a class and global variable in C++?
类中的静态成员变量和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;
}
但需要注意。您需要知道,如果定义静态类成员,则对于该类的所有实例都是通用的。因为实际上它是一个全局变量,只是在类的作用域中定义。
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 将静态全局变量声明为内联有什么意义吗?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 类中的静态成员变量和C++中的全局变量有什么区别?
- 全局变量和内部类有什么区别?
- C 我应该做什么而不是全局变量
- 我什么时候可以确定一个 constexpr 全局变量会像 C 宏一样被"forgotten"?
- 动态链接共享库中的全局变量和静态变量会发生什么情况
- C++:全局变量与局部变量.使用什么
- 什么时候全局变量被认为是好的/推荐的做法
- 在全局变量上使用placement new时,有什么不正确的地方吗
- 数学运算中的全局变量初始化,机器做什么
- 存储在全局变量中的数据与存储在堆中的数据有什么区别?
- 什么时候初始化thread_local全局变量?
- 全局变量,它们到底是什么