哪里出问题了#include <iostream> #include <string.h> #include <vector> #include <ctime> using namespace std; class Bank{ private: string account; time_t create_time; double balance; vector< pair<time_t, double> > history; public : Bank(string accountNumber,double balance){ accountNumber= accountNumber; this->balance = balance; create_time = time(NULL); } void deposit(double amount){ balance +=amount; time_t deposit_time =time(NULL); history.emplace_back(make_pair(deposit_time, amount)); } bool Withdraw(double amount){ if(amount>balance){ return false; } balance -=amount; time_t Withdraw_time =time(NULL); history.emplace_back(make_pair(Withdraw_time, -amount)); return true; } void printHistory() { for (auto& record : history) { string type = (record.second > 0) ? "存入" : "取出"; cout << "在" << ctime(&record.first) << type << abs(record.second) << "元" << endl; } } double GetBalance()const{ return balance; } time_t GetCreateTime() const { return create_time; } vector< pair<time_t, double> >GetHistory()const{ return history; } int main(){ Bank account("12345",100.0); account.deposit(50.0); account.Withdraw(125.0); account.printHistory(); return 0; } };
时间: 2024-01-14 09:01:56 浏览: 151
这段代码存在几个问题:
1. `main()` 函数应该在类外部定义,而不是在 `Bank` 类中定义。
2. 在 `Bank` 的构造函数中,应该使用 `this->account = accountNumber;` 而不是 `accountNumber= accountNumber;`。
3. 在 `printHistory()` 函数中,应该使用 `ctime(&(record.first))` 而不是 `ctime(&record.first)`。
4. `Withdraw()` 函数中,应该将 `return true` 和 `history.emplace_back()` 语句的位置进行交换,否则会导致在取款失败时,仍然记录了一条负数金额的记录。
修改后的代码如下所示:
```c++
#include <iostream>
#include <string.h>
#include <vector>
#include <ctime>
using namespace std;
class Bank {
private:
string account;
time_t create_time;
double balance;
vector<pair<time_t, double>> history;
public:
Bank(string accountNumber, double balance) {
this->account = accountNumber;
this->balance = balance;
create_time = time(NULL);
}
void deposit(double amount) {
balance += amount;
time_t deposit_time = time(NULL);
history.emplace_back(make_pair(deposit_time, amount));
}
bool Withdraw(double amount) {
if (amount > balance) {
return false;
}
balance -= amount;
time_t Withdraw_time = time(NULL);
history.emplace_back(make_pair(Withdraw_time, -amount));
return true;
}
void printHistory() {
for (auto& record : history) {
string type = (record.second > 0) ? "存入" : "取出";
cout << "在" << ctime(&(record.first)) << type << abs(record.second) << "元" << endl;
}
}
double GetBalance() const {
return balance;
}
time_t GetCreateTime() const {
return create_time;
}
vector<pair<time_t, double>> GetHistory() const {
return history;
}
};
int main() {
Bank account("12345", 100.0);
account.deposit(50.0);
account.Withdraw(125.0);
account.printHistory();
return 0;
}
```
阅读全文