访问修饰符适用于静态类函数吗?
我刚刚遇到了受保护的静态类函数的代码,如下所示:
class C {
...
protected:
static int fun() { ... }
};
我很好奇静态类函数是否可以具有访问修饰符,这意味着什么?因为它们是类全局变量而不是预实例。
谢谢,博达·西多。
I just came across code that had protected
static class functions, as in:
class C {
...
protected:
static int fun() { ... }
};
I got curious if static class functions could have access modifiers and what would it mean? Since they are class globals and not pre-instance.
Thanks, Boda Cydo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++ 中的访问修饰符不能针对每个实例工作。他们总是按班级工作。一直都是这样。这使得它们也适用于静态成员是完全合乎逻辑的。
这是一个相当流行的误解,认为 C++ 中的访问保护应该以某种方式针对每个实例起作用,这似乎也激发了您的问题。
Access modifiers in C++ do not work per-instance. They always work per-class. That is how it's always been. Which makes it perfectly logical to have them apply to static members as well.
It is a rather popular misconception that access protection in C++ is somehow supposed to work per-instance, which seems to be what inspired your question as well.
它仍然具有相同的目的:只有派生类可以调用该静态函数。
It still serves the same purpose: Only derived classes can call that static function.
这意味着受保护:静态函数可以从该类的其他成员函数或派生类的成员函数访问。
It means protected: static functions can be accessed from other member functions of that class or from the member functions of the derived classes.