前言

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

正文

内部类

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

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

  1. class BiuMall {
  2. public:
  3. class BiuStore {
  4. private:
  5. float score;
  6. public:
  7. int number;
  8. //score私有的,因此提供方法进行访问
  9. void setSocre(float score) {
  10. this->score = score;
  11. }
  12. float getScore() {
  13. return score;
  14. }
  15. };
  16. //定义内部类对象
  17. BiuStore biuStore;
  18. void setNumber(int number) {
  19. biuStore.number = number;
  20. }
  21. void setScore(int score) {
  22. //biuStore.score = score; //错误,不可以访问内部类私有变量
  23. biuStore.setSocre(score);
  24. }
  25. void printfInfo() {
  26. std::cout << biuStore.number << " --> " << biuStore.getScore() << std::endl;
  27. }
  28. };
复制

上面BiuStore是一个内部类。

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

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

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

局部类

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

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

  1. int main()
  2. {
  3. int age = 5;
  4. static int age_static = 10;
  5. //局部类
  6. class BiuMall{
  7. public:
  8. //static int number_static; //错误,不允许静态数据成员声明
  9. int number;
  10. void pintfInfo() {
  11. std::cout << number << std::endl;
  12. std::cout << age_static << std::endl;
  13. //std::cout << age << std::endl; //错误: 不允许引用封闭函数的局部变量
  14. }
  15. static int getNumber();
  16. };
  17. //错误,不能在成员函数 的类外部重新声明该函数
  18. //int BiuMall::getNumber() {
  19. // return 1;
  20. //}
  21. BiuMall biumall;
  22. biumall.number = 1;
  23. biumall.pintfInfo();
  24. }
  25. void test() {
  26. // BiuMall biumall; // 错误,找不到BiuMall的定义
  27. }
复制

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

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

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

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

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

参考文

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

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

相关文章

暂无评论

none
暂无评论...