我試圖從「內部」(本地)類的方法訪問「外部」類的屬性,但是失敗。嘗試從本地類方法訪問屬性時出現編譯錯誤
這無法編譯
class outer
{
public:
std::string name;
class inner
{
public:
void hello();
};
void dostuff();
};
void outer::inner::hello(){std::cout << "Hello " << name << "\n";}
void outer::dostuff(){inner instanceInner; instanceInner.hello();}
int main()
{
outer instanceOuter;
instanceOuter.name = std::string("Alice");
instanceOuter.dostuff();
return 0;
}
編譯錯誤:
9:21: error: invalid use of non-static data member 'outer::name'
21:53: error: from this location
我真的不希望name
爲靜態成員,但我真的不介意我的特定目的outer
是一個單身人士。於是,我試着用static std::string name;
並獲得
編譯錯誤:
/tmp/ccqVKxC4.o: In function `outer::inner::hello()':
:(.text+0x4b): undefined reference to `outer::name'
/tmp/ccqVKxC4.o: In function `main':
:(.text.startup+0x1f): undefined reference to `outer::name'
collect2: error: ld returned 1 exit status
你能幫助我嗎?
感謝您的回答。我看不出你的「hello」和我的區別(void outer :: inner :: hello(){std :: cout <<「Hello」<< name <<「\ n」;}')。我有什麼誤解嗎? –
我只是指出你的錯誤謊言和爲什麼發生。如果你現在檢查我的編輯,你可以看到一個建議來管理這@ @ Remi.b – 0xDEFACED
我可以傳遞'name'給函數。我試圖不通過它。原因是我有一個相對較長的代碼(約1000行),我只是將整個想法包裹在一個外部類中。我希望不必將外部類的每個屬性都傳遞給每個函數調用。請注意,將所有參數作爲參數傳遞最終可能會降低性能,對於那些可能有5個參數作爲參考傳遞的小函數,這些小函數也會被重複調用。否則最終可能無法做到(除非通過外部類的實例調用每個屬性) –