开发者

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

How can classes in C++ be decl开发者_Python百科ared public, private, or protected?


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:

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


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.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜