嵌套类定义

参考:Nested Class Declarations

声明

一个类可以在另一个类的范围内声明,这样的类称为嵌套类。嵌套类被视为在封闭类的范围内,并可在该范围内使用。若要从其直接封闭作用域以外的作用域引用嵌套类,必须使用完全限定名

class Cls {
public:
    class NestA {
    public:
        void print() {
            std::cout << "NestA" << std::endl;
        }
    };

    class NestB {
    public:
        void print() {
            std::cout << "NestB" << std::endl;
        }
    };

    void print() {
        NestA nestA;
        NestB nestB;
        nestA.print();
        nestB.print();
        std::cout << "Cls" << std::endl;
    }
};

int main() {
    Cls cls;
    cls.print();

    Cls::NestA nestA;
    nestA.print();
    Cls::NestB nestB;
    nestB.print();
}

使用

  • 对于封闭类中的成员/函数,嵌套类可以直接使用
  • 对于其他类的成员/函数,必须通过指针、引用或对象名来使用
  • 对于嵌套类的友元函数,其仅能访问嵌套类,不能访问封闭类