C++ 巢狀類簡單測試

double64發表於2024-08-30
class Dog
{
public:
    class Animal
    {
    public:
        Animal(Dog* dog)
        {
            m_Dog = dog;
            m_Age = 1;
            m_Name = dog->m_Info; // 可以訪問宿主類物件
        }
        string m_Name;
        int getAge()
        {
            return m_Age;
        }
    private:
        Dog* m_Dog;
        int m_Age;
    };
public:
    Dog() :m_Info("哮天犬"), m_Animal(this)
    {
    }
    void showInfo()
    {
        cout << m_Animal.m_Name << endl;
        //cout << m_Animal.m_Age << endl; /*不可訪問*/
        cout << m_Animal.getAge() << endl;
    }
private:
    string m_Info;
    Animal m_Animal;
};


int main()
{
    Dog dog;
    dog.showInfo();

    return 0;
}

輸出:

哮天犬
1

內部類巢狀類可以訪問外部宿主類的私有成員。

相關文章