前言

简单记录一下C++中的内部类局部类相关知识,方便后续自己查阅或学习。

正文

内部类

在一个类A内部定义另外一个类B,那么类B就可以成为内部类,内部类又叫嵌套类。

内部定义跟类定义一样,没有任何差异,除了放在类中。

class BiuMall {
public:
    class BiuStore {
    private:
        float score;
    public:
        int number;
        //score私有的,因此提供方法进行访问
        void setSocre(float score) {
            this->score = score;
        }
        float getScore() {
            return score;
        }
    };
    //定义内部类对象
    BiuStore biuStore;
    void setNumber(int number) {
        biuStore.number = number;
    }
    void setScore(int score) {
        //biuStore.score = score; //错误,不可以访问内部类私有变量
        biuStore.setSocre(score);
    }
    void printfInfo() {
        std::cout << biuStore.number << " --> " << biuStore.getScore() << std::endl;
    }
};

上面BiuStore是一个内部类。

  1. 外部内不能访问内部类private修饰的成员函数或成员变量

    void setScore(int score) {
        //biuStore.score = score; //错误,score是private修饰的,外部类不可以访问内部类私有变量
        biuStore.setSocre(score);
    }
  2. 内部类值运行在其外部类中使用,对于其他类中是不可见的

    int main()
    {
        //BiuStore biuStore; //错误,无法直接使用
    
        BiuMall::BiuStore biuStore; //可以,但要这样使用干嘛要定义到类内部呢?
    }

局部类

把定义在函数(或叫方法)中的类叫局部类。

局部类,类如其名,作用域直在局部范围。

int main()
{
    int age = 5;
    static int age_static = 10;

    //局部类
    class BiuMall{
    public:
        //static int number_static; //错误,不允许静态数据成员声明
        int number;
        void pintfInfo() {
            std::cout << number << std::endl;
            std::cout << age_static << std::endl;
            //std::cout << age << std::endl; //错误: 不允许引用封闭函数的局部变量
        }
        static int getNumber();
    };

    //错误,不能在成员函数 的类外部重新声明该函数
    //int BiuMall::getNumber() {
    //  return 1;
    //}

    BiuMall biumall;
    biumall.number = 1;
    biumall.pintfInfo();
}

void test() {
    // BiuMall biumall; // 错误,找不到BiuMall的定义
}

上面的BiuMall就是一个局部类,定义在main()中。

  1. 作用仅在函数内部使用

  2. 所有的成员(成员变量或函数)只能定义在内部

  3. 不允许定义static成员变量

  4. 除了static变量,局部类不可以访问函数的局部变量。

参考文

  1. 《C++从入门到精通(第6版)》

  2. C++内部类,局部类

相关文章

暂无评论

none
暂无评论...