为什么我们不必像在 C++ 中声明静态变量那样声明静态函数?
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;
}
};
并且以下主要函数使用同一 cpp 文件中的结构 (main.cpp):
int main()
{
Toto::Print();
}
构建它会出现以下错误:
错误 LNK2001 无法解析的外部符号“public: static int Toto::a”
我从https://en.cppreference.com/w/cpp/language/static了解到
Static members of a class are not associated with the objects of the
class
因此,我被告知我们必须在结构之外定义变量 Toto::a,在
翻译单位如下:
int Toto::a;
来源相同
Static member functions are not associated with any object.
还有那个
Static data members are not associated with any object.
为什么我必须定义静态变量而不是静态函数?
静态成员函数是汇编级的普通函数。不同的只是它们里面不存在的隐藏指针'this'。它们基本上是全局函数,像 class 名称的 C++ 范围内的任何其他非静态或非成员(而不是内联)函数一样存在。函数范围是 C++ 的东西,它们不在 CPU 级别。
静态变量不同。它们在创建任何 class 对象之前就存在。创建 class 实例时不会创建它们。它们作为全局变量存在。
也许这样做是为了强调这种差异。
考虑以下结构:
struct Toto {
static int a;
static void Print() {
std::cout << a;
}
};
并且以下主要函数使用同一 cpp 文件中的结构 (main.cpp):
int main()
{
Toto::Print();
}
构建它会出现以下错误:
错误 LNK2001 无法解析的外部符号“public: static int Toto::a”
我从https://en.cppreference.com/w/cpp/language/static了解到
Static members of a class are not associated with the objects of the class
因此,我被告知我们必须在结构之外定义变量 Toto::a,在 翻译单位如下:
int Toto::a;
来源相同
Static member functions are not associated with any object.
还有那个
Static data members are not associated with any object.
为什么我必须定义静态变量而不是静态函数?
静态成员函数是汇编级的普通函数。不同的只是它们里面不存在的隐藏指针'this'。它们基本上是全局函数,像 class 名称的 C++ 范围内的任何其他非静态或非成员(而不是内联)函数一样存在。函数范围是 C++ 的东西,它们不在 CPU 级别。
静态变量不同。它们在创建任何 class 对象之前就存在。创建 class 实例时不会创建它们。它们作为全局变量存在。
也许这样做是为了强调这种差异。