1. 定义一个类来表示银行账户,数据成员包括储户姓名、账号(使用字符串)和存款。成员函数执行如下操作:
- 创建一个对象并将其初始化;
- 显示储户姓名、账号和存款;
- 存入参数指定的存款;
- 取出参数指定的款项。
请提供类声明,并为类提供方法定义,编写一个小程序来演示所有的特性。
注意:默认参数位于函数原型中,而不是函数定义中。
// account.h 银行账户
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
class Account {
private:
enum { Size_name = 20, Size_number = 40 };
char name[Size_name]; // 储户姓名
char number[Size_number]; // 账号
double deposit; // 存款
public:
Account(const char* na, const char* nu, double de = 0.0);
Account();
~Account();
void store(double n);
void withdraw(double n);
void show() const;
};
#endif // !ACCOUNT_H_
// account.cpp
#include <iostream>
#include <cstring>
#include "account.h"
Account::Account(const char* na, const char* nu, double de) {
strncpy(name, na, Size_name - 1);
name[Size_name - 1] = '\0';
strncpy(number, nu, Size_number - 1);
number[Size_number - 1] = '\0';
deposit = de;
}
Account::Account() {
strcpy(name, "no name");
strcpy(number, "no number");
deposit = 0.0;
}
Account::~Account() {
}
void Account::store(double n) {
deposit += n;
}
void Account::withdraw(double n) {
if (deposit < n)
std::cout << "There is not enough money for withdrawal.\n" << "EXIT" << std::endl;
else deposit -= n;
}
void Account::show() const {
using std::cout;
using std::endl;
cout << "The depositor's name is: " << name
<< " and the account number is " << number
<< ". The deposit is " << deposit << ".\n";
}
// 使用类
#include "account.h"
int main() {
Account ac1 = Account("Mary", "131675", 70000.0);
Account ac2;
ac1.show();
ac2.show();
ac1.store(80);
ac1.show();
ac2.withdraw(90.9);
ac1.withdraw(79.83);
ac1.show();
ac2.show();
ac1 = ac2;
ac1.show();
return 0;
}
2. 提供未定义的方法的代码,完成这个类的实现。
// person.h
#ifndef PERSON_H_
#define PERSON_H_
#include <iostream>
class Person {
private:
static const int LIMIT = 25;
std::string lname; // last name
char fname[LIMIT]; // first name
public:
Person() { lname = ""; fname[0] = '\0'; } // #1
Person(const std::string& ln, const char* fn = "Heyyou"); // #2
void Show() const; // firstname, lastname format
void FormalShow() const; // lastname, firstname format
};
#endif // !PERSON_H_
#include <iostream>
#include <string>
#include "person.h"
Person::Person(const std::string& ln, const char* fn) {
lname = ln;
strncpy(fname, fn, LIMIT - 1);
fname[LIMIT - 1] = '\0';
}
void Person::Show() const {
using std::cout;
cout << fname << " " << lname << '\n';
}
void Person::FormalShow() const {
std::cout << lname << " " << fname << std::endl;
}
#include "person.h"
int main() {
using std::cout;
using std::endl;
Person one;
Person two(&