我不能找出爲什麼以下(大大簡化)代碼返回錯誤error: 'm_sID' was not called in this scope
:C++類屬性未定義用於非存取方法
#include <iostream>
#include <string>
//////////////////////////////////////////
//header
class Person {
private:
std::string m_sID;
public:
//constructor
Person(std::string sID);
//getter
std::string getID() { return m_sID; }
//setter
void setID(std::string sID) { m_sID = sID; }
void comparePersonID();
};
//////////////////////////////////////////
//implementation
Person::Person(std::string sID) {
setID(sID);
}
void comparePersonID() {
if (m_sID == "12345")
std::cout << "success!" << std::endl;
}
//////////////////////////////////////////
//main
int main() {
std::string myStr = "1";
Person aPerson(myStr);
aPerson.setID("12345");
aPerson.comparePersonID();
}
由於comparePerson()
是Person
類的成員函數,當不可它能夠訪問私有變量m_sID
?
或者問這個問題的另一種方式:我知道,在Ruby中,可以得到這樣的事情通過調用self.getID
(或東西左右)工作,但什麼是工作相當於self
在C++那編譯並正確執行。
啊確定,使得有很大的意義。來自更高級別的語言,我期望'Person'頭文件中的函數聲明足以讓編譯器推斷範圍,但很明顯這會導致問題,如果在每個函數中有兩個相同名稱的方法單獨的課程。 – JDRomano2 2015-02-10 18:49:21