c++ - 从成员结构的成员函数中访问类的成员?

标签 c++ initialization inner-classes

来自以下代码:

#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独立于封闭类。

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

关于c++ - 从成员结构的成员函数中访问类的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381710/

相关文章:

c++ - 如何确保返回 vector <unique_ptr> 的常量

c++ - 使用 "auto"的声明是否匹配使用具体类型说明符的 extern 声明?

C++组合和初始化

unit-testing - 测试期间的 Scalatra Servlet init() (Jetty ServletTester)

java - 内部类的目的是什么

c++ - 将 'new[]' 智能替换为 make_unique

c++ - 为什么我在 __int64 变量上 & (anding) 位时得到奇怪的结果?

C++:首先调用/初始化哪个?其成员变量的类构造函数或构造函数?

java - 为什么我无法访问匿名内部类中重写的公共(public)字段?

Java - 从处理程序引用外部类