内部/嵌套类 - 私有和公共之间的区别

时间:2013-11-14 13:19:01

标签: c++

我有内部嵌套类,它是私有的:

   class Client{
   private:
      class Inner;
      Inner *i;

究竟会发生什么,如果我将内部公共和内部*我保持私密?会发生什么,以及在程序执行方面会产生什么影响?

2 个答案:

答案 0 :(得分:1)

如果您将Client::Inner公开,则可以访问其名称。它对i;

的可访问性没有影响
class Client{
public:
    class Public;
private:
    class Private;
    Public a;
    Private b;
};

int main()
{
    Client::Public a;
    Client::Private b; // error

    Client c;
    c.a;  // error
    c.b;  // error
}

答案 1 :(得分:1)

考虑以下用例:

class Client
{
private:
    class Inner {};
    Inner *i;

    class Inner2 {};
public:
    class Inner3 {};
    Inner3 *j;

public:
    Inner2 *k;
};

void main()
{
    Client c;

    c.i = nullptr; //error: you cant access the private members

    c.j = nullptr; //ok: member is public
    c.k = nullptr; //ok: same here, member is public, even if it's type is private

    Client::Inner3 i3;//ok: to declare since Inner3 is declared public

    Client::Inner2 i3;//error: can't access private members of type declarations

}

除此之外,程序的执行在任何情况下都不受私人/公共或受保护的影响。