2013-09-24 165 views
0

我是新來的班級我創建了一個新班級來跟蹤不同的帳戶詳細信息,但是有人告訴我,班級的成員應該是私人的,並且要使用getter和setter功能。我看了很多例子,但似乎無法弄清楚如何訪問我的主程序中的私人成員。我希望用戶輸入帳戶的不同參數,如果我將其成員公開,它就可以正常工作,我該如何添加getter和setter。我的班級的私人成員和主要的什麼是唯一的東西,我需要的一切,我試圖讓它工作,但我真的失去了。使用矢量,因爲一旦我得到它的工作,我會寫一個循環來獲取多個帳戶,但現在我只是想將數據Im來獲取輸入存儲訪問班級的私人成員

class account 

{ public    
     friend void getter(int x); 

    private: 
     int a; 
     char b; 
     int c; 
     int d; 
}; 

using namespace std; 

void getter (int x) 
{ 

} 

int main() 
{ 
    vector <account> data1 (0); 
    account temp; 

    cin>>temp.a>>temp.b>>temp.c>>temp.d; 
    data1.push_back(temp); 

    return 0; 
} 
+1

誰讓你使用getter和setter方法? –

回答

4

你應該有一個朋友運算符重載:

class account 
{ 
    friend std::istream& operator>> (std::istream &, account &); 
public: 
    // ... 
}; 

std::istream& operator>> (std::istream& is, account& ac) 
{ 
    return is >> ac.a >> ac.b >> ac.c >> ac.d; 
} 

int main() 
{ 
    account temp; 

    std::cin >> temp; 
} 
+0

即時通訊仍然收到錯誤'int account :: a'是私人的 – Tjarmws

+0

@JesseWashington做'std :: cin >> temp;'就像我有。 – 0x499602D2

+0

@JesseWashington它有效嗎? – 0x499602D2

1

這裏是獲取/例子設置方法:

class account 

{ public    
     int getA() const { return a; } 
     void setA(int new_value) { a = new_value; } 
     int getB() const { return b; } 
     void setB(int new_value) { b = new_value; } 
     int getC() const { return c; } 
     void setC(int new_value) { c = new_value; } 
     int getD() const { return d; } 
     void setD(int new_value) { d = new_value; } 

    private: 
     int a; 
     char b; 
     int c; 
     int d; 
}; 

從你會使用主:

int main() 
{ 
    vector <account> data1 (0); 
    account temp; 
    int a,b,c,d; 

    cin >> a >> b >> c >> d; 
    temp.setA(a); 
    temp.setB(b); 
    temp.setC(c); 
    temp.setD(d); 
    data1.push_back(temp); 

    return 0; 
} 

注:無論其在這樣的情況下,get/set方法是一個好主意是另一個問題。

+0

那麼如何使用cin >> temp.a >> temp.b >> temp.c >> temp.d;我仍然得到錯誤無法訪問私人會員a b c和d; – Tjarmws

+0

@JesseWashington:我已經添加了一個例子。 –

+0

@JesseWashington它看起來像是誤解了getter的用途:這是一種公共方法,您可以調用它來返回私有成員值的值。正如Vaughn Cato的例子所指出的那樣。 –