2009-11-14 72 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