从成员结构的成员函数中访问 class 的成员?

Accessing a class's member from within a member struct's member function?

来自以下代码:

#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() 内)

Nested classes 独立于封闭的 class。

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

所以你需要传递一个包含class的实例给它,或者让它持有一个(作为成员)。

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

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