0

セッターメソッドで文字列を設定する際に、別の方法で行う必要があることはありますか? これは私のクラスです:

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

それを「セッター」と呼ばないでください:)?パラメーターを使用せず、標準入力からデータを読み取りますが、セッターの通常のセマンティクスは、パラメーターを取得して適切なフィールドに割り当てることです。これは「readData()」と呼ばれる場合があります

于 2009-11-14T01:25:38.657 に答える
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();
}
于 2009-11-14T02:21:10.260 に答える