C++类(公共类、私有类和受保护类)
C++ 中的类如何声明为 public
、private
或 protected
?
How can classes in C++ be declared public
, private
, or protected
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,不存在像 Java 或 C# 中那样整个类具有访问说明符的概念。如果一段代码具有类的可见性,则它可以引用该类的名称并对其进行操作。也就是说,这有一些限制。例如,仅仅因为您可以引用一个类并不意味着您可以实例化它,因为构造函数可能被标记为私有。同样,如果该类是在另一个类的私有或受保护部分中声明的嵌套类,则该类将无法从该类及其友元外部访问。
In C++ there is no notion of an entire class having an access specifier the way that there is in Java or C#. If a piece of code has visibility of a class, it can reference the name of that class and manipulate it. That said, there are a few restrictions on this. Just because you can reference a class doesn't mean you can instantiate it, for example, since the constructor might be marked private. Similarly, if the class is a nested class declared in another class's private or protected section, then the class won't be accessible outside from that class and its friends.
通过将一个类嵌套在另一个类中:
By nesting one class inside another:
您可以通过简单地不将其接口发布给客户端来实现“私有类”。
我知道没有办法创建“受保护的类别”。
You can implement "private classes" by simply not publishing their interface to clients.
I know of no way to create "protected classes".
这取决于您指的是成员还是继承。因此,您不能拥有
'私有类'
。或者继承:
It depends if you mean members or inheritance. You can't have a
'private class'
, as such.Or inheritance: