#include <iostream> using namespace std; class Savingsaccount { public: char id; float balance; char name; Savingsaccount(char _id,float _balance, char _name) { id = _id; balance = _balance; name = _name; } }; int main() { Savingsaccount s1("张三",10.00, "张文"); return 0; }优化代码
时间: 2024-01-12 11:05:18 浏览: 70
首先需要修改 Savingsaccount 类的构造函数参数类型,将 char 类型改为 string 类型,同时添加默认构造函数和成员函数来获取和设置私有成员变量。优化后的代码如下:
```
#include <iostream>
using namespace std;
class Savingsaccount {
private:
string id;
float balance;
string name;
public:
Savingsaccount() {}
Savingsaccount(string _id, float _balance, string _name) {
id = _id;
balance = _balance;
name = _name;
}
string getId() const {
return id;
}
void setId(string _id) {
id = _id;
}
float getBalance() const {
return balance;
}
void setBalance(float _balance) {
balance = _balance;
}
string getName() const {
return name;
}
void setName(string _name) {
name = _name;
}
};
int main() {
Savingsaccount s1("001", 10.00, "张三");
cout << s1.getId() << " " << s1.getBalance() << " " << s1.getName() << endl;
return 0;
}
```
这样做的好处是,代码更加规范、易读,同时也方便后续的扩展和维护。
阅读全文