C++ 类(公共、私有和受保护)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4855422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:47:22  来源:igfitidea点击:

C++ classes (public, private, and protected)

c++privatepublicprotectedaccess-modifiers

提问by Simplicity

How can classes in C++ be declared public, private, or protected?

如何可以在C ++类中声明publicprivateprotected

回答by templatetypedef

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.

在 C++ 中,没有像在 Java 或 C# 中那样具有访问说明符的整个类的概念。如果一段代码具有类的可见性,它可以引用该类的名称并对其进行操作。也就是说,对此有一些限制。仅仅因为您可以引用一个类并不意味着您可以实例化它,例如,因为构造函数可能被标记为私有。类似地,如果该类是在另一个类的私有或受保护部分中声明的嵌套类,则该类将无法从该类及其朋友的外部访问。

回答by Benjamin Lindley

By nesting one class inside another:

通过将一个类嵌套在另一个类中:

class A
{
public:
    class B {};
protected:
    class C {};
private:
    class D {};
};

回答by The Communist Duck

It depends if you mean members or inheritance. You can't have a 'private class', as such.

这取决于您是指成员还是继承。你不能有'private class', 这样的。

class Foo
{
public:
Foo() {} //public ctr
protected:
void Baz() //protected function
private:
void Bar() {} //private function
}

Or inheritance:

或者继承:

class Foo : public Bar
class Foo : protected Bar
class Foo : private Bar

回答by Edward Strange

You can implement "private classes" by simply not publishing their interface to clients.

您可以通过简单地不向客户端发布它们的接口来实现“私有类”。

I know of no way to create "protected classes".

我知道没有办法创建“受保护的类”。