0

在 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();
}
4

2 回答 2

0

您是否从您的代码中收到任何错误,或者您只是要求最好的方法来做到这一点?确实,您应该将相关代码重构为它们的关联函数,以将控制台输入和输出保留在 main 方法中,并通过参数将数据传递给函数。但无论如何不重构试试这个:

#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();
}
于 2009-11-14T02:21:10.260 回答
0

不要称它为“二传手”:) ?它不接受任何参数并从标准输入读取数据,而对于 setter,通常的语义是接受一个参数并将其分配给适当的字段。这个可能被称为“readData()”

于 2009-11-14T01:25:38.657 回答