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

发布于 2024-10-15 07:12:39 字数 86 浏览 7 评论 0原文

C++ 中的类如何声明为 publicprivateprotected

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

九局 2024-10-22 07:12:39

在 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.

岛歌少女 2024-10-22 07:12:39

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

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

By nesting one class inside another:

class A
{
public:
    class B {};
protected:
    class C {};
private:
    class D {};
};
自控 2024-10-22 07:12:39

您可以通过简单地不将其接口发布给客户端来实现“私有类”。

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

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

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

浮华 2024-10-22 07:12:39

这取决于您指的是成员还是继承。因此,您不能拥有'私有类'

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

或者继承:

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文