2016-05-23 150 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); 
}