[英]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()
)
嵌套類獨立於封閉類。
但它是獨立的,並且沒有對封閉類的this指針的特殊訪問權限。
所以你需要將一個封閉類的實例傳遞給它,或者讓它保持一個(作為成員)。
void A::B::update(A* pa)
{
cout << pa->name;
}
void A::read()
{
m.update(this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.