为什么C++的内部类访问外部类的枚举类型成员会报错?怎样在内部类中正确使用外部类的枚举类型成员?


#include <iostream>

using namespace std;

enum Sex
{
    Man,
    Woman
};

class Outside
{
public:
    class Inside
    {
    public:
        void show(Outside obj)
        {
            cout << _b << endl;
            cout << _sex << endl;
            //cout << obj._sex << endl;
        }
    private:
        int _c;
    };
private:
    int _a = 1;
    static int _b;    //静态成员
    enum Sex _sex = Man;    //枚举成员
};

int Outside::_b = 2;

int main()
{
    Outside::Inside obj;
    return 0;
}

类变量不要在定义的时候初始化
另外 _sex是Outside类的私有变量,除了友元类,其它类是不能访问的
修改方法:
一是将_sex定义为public,然后cout<<obj._sex<<endl;
二是Outside类增加get方法,比如 enum Sex GetSex() {return _sex;}
然后cout<<obj.GetSex()<<endl;

让内部类的构造函数接受指向外部类的对象的指针,并将其存储在数据成员中以供以后使用。