![](/img/trans.png)
[英]Why do we need to define static variables of a class, but we don't define static variables when they are inside functions?
[英]Why don't we have to declare static functions the same way we need to declare static variables in c++?
考虑以下结构:
struct Toto {
static int a;
static void Print() {
std::cout << a;
}
};
以及以下主要 function 使用同一 cpp 文件 (main.cpp) 中的结构:
int main()
{
Toto::Print();
}
构建它会出现以下错误:
错误 LNK2001 未解析的外部符号“public: static int Toto::a”
我从https://en.cppreference.com/w/cpp/language/static了解到
Static class 的成员与 class 的对象没有关联
因此,我被告知我们必须在结构外部定义变量 Toto::a,在翻译单元中如下所示:
int Toto::a;
从同一来源说
Static 成员函数不与任何 object 关联。
然后
Static 数据成员不与任何 object 关联。
为什么我必须定义 static 个变量而不是 static 个函数?
Static 成员函数是汇编级的普通函数。 区别仅在于它们中不存在的隐藏指针“this”。 它们基本上是全局函数,像 class 名称的 C++ 范围内的任何其他非 static 或非成员(而非内联)function 一样存在。 Function 范围是 C++ 的东西,它们不在 CPU 级别。
Static 变量不同。 它们存在于任何 class object 创建之前。 创建 class 实例时不会创建它们。 它们作为全局变量存在。
也许这样做是为了强调这种差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.