在setter方法中设置字符串

时间:2009-11-14 01:11:33

标签: 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();
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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();
}