gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:31:41 27 4
gpt4 key购买 nike

来自以下代码:

#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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com