为什么我们不需要以相同的方式声明静态函数,以声明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”
我从<我了解a href =“ https://en.cppreference.com/w/cpp/language/static” rel =“ nofollow noreferrer”> https://en.cppreference.com/w/cpp/language/static/static 那
类的静态成员与 类
,因此,我被告知我们必须定义变量toto ::外部结构,在 翻译单元如下:
int Toto::a;
从同一来源中说明
静态成员函数与任何对象无关。
那
静态数据成员与任何对象无关。
为什么我必须定义静态变量而不是静态函数?
Consider the following struct:
struct Toto {
static int a;
static void Print() {
std::cout << a;
}
};
And the following main function using the struct in the same cpp file (main.cpp):
int main()
{
Toto::Print();
}
Building this gives the following error:
Error LNK2001 unresolved external symbol "public: static int Toto::a"
I understand from https://en.cppreference.com/w/cpp/language/static that
Static members of a class are not associated with the objects of the
class
And thus, I've been told we have to define the variable Toto::a outside the struct, in
the translation unit as follow:
int Toto::a;
From the same source it says that
Static member functions are not associated with any object.
And that
Static data members are not associated with any object.
Why do I have to define static variables but not static functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态成员函数是组装级别的普通函数。区别仅仅是隐藏的指针“ this”,而它们中不存在。它们基本上是全局函数,它们像其他任何非静态或非成员(而不是内联)功能一样,在类名称的C ++范围内。功能范围是C ++的东西,它们不在CPU级别。
静态变量不同。它们存在于创建任何类对象之前。创建类实例时,它们不是创建的。他们在那里是全球。
也许它已经完成了强调这种差异的方式。
Static member functions are ordinary functions at the assembly level. The difference is only the hidden pointer 'this' that does not exist in them. They are basically global functions that exist like any other non static or non member (and not inline) function within the C++scope of a class name. Function scopes are C++ thing, they are not there at the CPU level.
Static variables are different. They exist before any class object is created. They are not created when a class instance is created. They are there as globals.
Perhaps it's done the way it's done to emphasize that difference.