2009-11-14 98 views
0

在setter方法中設置字符串時需要做些什麼不同嗎?這是我的班級:在setter方法中設置字符串

class SavingsAccount 
{ 
public: 
    void setData(); 
    void printAccountData(); 
    double accountClosure() {return (accountClosurePenaltyPercent * accountBalance);} 
private: 
    int accountType; 
    string ownerName; 
    long ssn; 
    double accountClosurePenaltyPercent; 
    double accountBalance; 
}; 

void SavingsAccount::setData() 
{ 
    cout << "Input account type: \n"; 
    cin >> accountType; 
    cout << "Input your name: \n"; 
    cin >> ownerName; 
    cout << "Input your Social Security Number: \n"; 
    cin >> ssn; 
    cout << "Input your account closure penalty percent: \n"; 
    cin >> accountClosurePenaltyPercent; 
    cout << "Input your account balance: \n"; 
    cin >> accountBalance; 
} 


int main() 
{ 
    SavingsAccount newAccount; 
    newAccount.setData(); 
} 
+0

@Jet - 不要在每行之後加上'
'來格式化您的代碼。使用代碼塊功能(位於編輯框的頂部)。現在修復。 – 2009-11-14 01:22:10

+0

好的。我想知道是否有什麼東西。我不知道它在哪裏! – Crystal 2009-11-14 01:30:56

回答

0

不要稱它爲「setter」:)?它不採用任何參數並從標準輸入讀取數據,而設置者通常的語義是採取一個參數並將其分配給適當的字段。這個可能被稱爲「readData()」

0

您是否從您的代碼收到任何錯誤,或者您只是要求最好的方式來做到這一點?實際上,您應該將相關代碼重構爲相關函數,以保持主方法中的控制檯輸入和輸出,並通過參數將數據傳遞給函數。但無論如何不重構請試試這個:

#include <sstream> 
#include <iostream> 

using namespace std; 

class SavingsAccount 
{ 
public: 
    void setData(); 
    void printAccountData(); 
    double accountClosure() {return (accountClosurePenaltyPercent*accountBalance);} 
private: 
    int accountType; 
    string ownerName; 
    long ssn; 
    double accountClosurePenaltyPercent; 
    double accountBalance; 
}; 

void SavingsAccount::setData() 
{ 
stringstream str; 

cout << "Input account type: \n"; 
cin >> str; 
str >> accountType; // convert string to int 

cout << "Input your name: \n"; 
cin >> str; 
str >> ownerName; 

cout << "Input your Social Security Number: \n"; 
cin >> str; 
str >> ssn; // convert to long 

cout << "Input your account closure penalty percent: \n"; 
cin >> str; 
str >> accountClosurePenaltyPercent; // convert to double 

cout << "Input your account closure penalty percent: \n"; 
cin >> str; 
str >> accountClosurePenaltyPercent; // convert to double 

cout << "Input your account balance: \n"; 
cin >> str; 
str >> accountBalance; // convert to double 
} 

int main() 
{ 
SavingsAccount newAccount; 
newAccount.setData(); 
} 
+0

不是編譯錯誤,而是我不熟悉的運行時錯誤。它是: Assignment8_1(491)的malloc:***錯誤對象0x100006240:被釋放的指針沒有被分配 ***設置malloc_error_break斷點調試 中止陷阱 註銷 我想我不知道是什麼你可以按照像int或double這樣的方式設置字符串。謝謝! – Crystal 2009-11-14 02:34:49

+0

您可能還想考慮爲SavingsAccount類使用構造函數和析構函數,以便您可以使用new和delete關鍵字並控制內存分配。這可以幫助您避免運行時錯誤。 – SimonDever 2009-11-14 02:53:59