来自以下代码:
#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/