简体   繁体   中英

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

From the following code:

#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;
}

When I compile, I receive the following error:

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;

How do I go about printing the A's name variable from within a member struct's member function? (Specifically from within A::B::update() )

Nested classes is independent from the enclosing class.

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

So you need to pass an instance of enclosing class to it, or let it hold one (as member).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM