C++ 嵌套类与外围类间的成员访问

/**
 * 嵌套类与外围类间的成员访问
 * 1. 外围类不能访问嵌套类的非静态数据成员, 反之亦然;
 * 2. 外围类可以访问嵌套类的静态成员,但必须加上名字限定,嵌套类可以访问外围类的静态成员
 * 3. 在外围类的成员函数中,可以直接调用嵌套类的静态成员函数,但调用非静态成员函数必须借助嵌套类对象来调用
 * 4. 在嵌套类的成员函数中,可以直接调用外围类的静态成员函数,但不能调用非静态函数,即使加enclose::也不行
 *
 */

#include <iostream>
using namespace std;

int x,y; // globals
class enclose { // enclosing class
    int x; // note: private members
    static int s;
 public:
    int z;
    struct inner { // nested class
      int m;
      static int n;

      inner() {
        std::cout << "this is inner's constructor..." << std::endl;
      }

      void f(int i) {
        std::cout << "this is inner's function f..." << std::endl;
        // x = i; // Error: can't write to non-static enclose::x without instance
        // z = i; //Error
        // std::cout << z << std::endl; //Error :invalid use of non-static data member ‘enclose::z’
        int a = sizeof x; // Error until C++11,
                          // OK in C++11: operand of sizeof is unevaluated,
                          // this use of the non-static enclose::x is allowed.
        s = i;   // OK: can assign to the static enclose::s,嵌套类可以访问外围类的静态成员
        ::x = i; // OK: can assign to global x
        y = i;   // OK: can assign to global y
      }
      void g(enclose* p, int i) {
          p->x = i; // OK: assign to enclose::x
      }

      void h() {
        std::cout << "this is inner's function h..." << std::endl;
      }

      static void i() {
        std::cout << "this is inner's static function i..." << std::endl;
      }

      void j() {
        std::cout << "this is inner's  function j..." << std::endl;
        enclose_d();
        // enclose_c();//嵌套类可以调用外围类的静态成员函数,但不能调用非静态函数,即使加enclose::也不行
      }

    };

    void enclose_b() {
      inner();
    }
    void enclose_a() {
      inner in;
      in.h();//非静态函数必须借助嵌套类的对象来调用
    }

    void enclose_c() {
      inner::i();//嵌套类的静态函数可以直接调用
      std::cout << inner::n << std::endl;//外围类可以访问嵌套类的静态成员,但必须加上名字限定
    }

    static void enclose_d() {
      std::cout << "this is enclose's static function enclose_d..." << std::endl;
    }

    // void enclose_e() {
    //   std::cout << inner::m << std::endl;// Error: m is not declare in this scope 外围类不能访问嵌套类的非静态数据成员,即使加了名字限定也不行
    // }

};
int main(int argc, char const *argv[]) {
  /* code */
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值