2016-05-23 40 views
1

從下面的代碼:從成員struct的成員函數中訪問類的成員?

#include <iostream> 
#include <string> 
using namespace std; 

class A 
{ 
    public: 
    A() { name = "C++"; } 
    void read(); 

    private: 
    string name; 
    struct B 
    { 
     char x, y; 
     int z; 
     void update(); 
    } m, n, o; 
}; 

void A::B::update() 
{ 
    cout << this->A::name; 
} 

void A::read() 
{ 
    m.update(); 
} 

int main() { 
    A a; 
    a.read(); 
    return 0; 
} 

當我編譯,我收到以下錯誤:

prog.cpp: In member function 'void A::B::update()': 
prog.cpp:23:19: error: 'A' is not a base of 'A::B' 
    cout << this->A::name; 

我該如何去約一個成員結構的成員函數內打印A的name變量? (具體來自A::B::update()內)

回答

3

Nested classes獨立於封閉類。

but it is otherwise independent and has no special access to the this pointer of the enclosing class.

所以你需要傳遞一個封閉類的實例給它,或讓它保持一個(作爲成員)。

void A::B::update(A* pa) 
{ 
    cout << pa->name; 
} 

void A::read() 
{ 
    m.update(this); 
}