51 C++ Primer Plus(第六版)第十章 编程练习答案
1
BankAccount.h
#pragma once
#include<iostream>
#include<string>
class BankAccount
{
private:
string m_Name;
string m_Account;
double m_Money;
public:
BankAccount();
BankAccount(const string& name, const string& account, double money);
void ShowAccount() const;
void AddMoney(double money);
void SubtractMoney(double money);
};
exercise01_BankAccount.cpp
#include<iostream>
using namespace std;
#include"BankAccount.h"
BankAccount::BankAccount()
{
}
BankAccount::BankAccount(const string& name, const string& account, double money)
{
this->m_Name = name;
this->m_Account = account;
if (money < 0)
{
cout << "Money can't be negative!\n";
this->m_Money = 0;
}
else
this->m_Money = money;
}
void BankAccount::ShowAccount() const
{
cout << "Name: " << this->m_Name << "\t" << "Account: " << this->m_Account << "\t"
<< "Money: " << this->m_Money << endl;
}
void BankAccount::AddMoney(double money)
{
if (money < 0)
cout << "Money can't be negative!\n";
else
this->m_Money += money;
}
void BankAccount::SubtractMoney(double money)
{
if (money < 0)
cout << "Money can't be negative!\n";
else if (money > this->m_Money)
cout << "This account doesn't have so much money!\n";
else
this->m_Money -= money;
}
exercise01.cpp
#include<iostream>
using namespace std;
#include"BankAccount.h"
int main()
{
BankAccount ba1;
BankAccount ba2("张三", "001", 10000);
ba2.ShowAccount();
BankAccount ba3("李四", "002", -10000);
ba3.ShowAccount();
ba2.AddMoney(-10000);
ba2.ShowAccount();
ba2.AddMoney(10000);
ba2.ShowAccount();
ba2.SubtractMoney(-20000);
ba2.ShowAccount();
ba2.SubtractMoney(30000);
ba2.ShowAccount();
ba2.SubtractMoney(20000);
ba2.ShowAccount();
ba1 = ba2;
ba1.ShowAccount();
return 0;
}
2
Person.h
#pragma once
#include<iostream>
using namespace std;
class Person
{
private:
static const int Limit = 25;
string lname;
char fname[Limit];
public:
Person() {
lname = " "; fname[0] = '\0'; }
Person(const string& ln, const char* fn = "Heyyou");
void Show() const;
void FormalShow() const;
};
exercise02_Person.cpp
#include<iostream>
#include"Person.h"
using namespace std;
Person::Person(const string& ln, const char* fn)
{
lname = ln;
strcpy_s(fname, fn);
}
void Person::Show() const
{
cout << "firstname lastname format\n";
cout << "Name: " << fname << " " << lname << endl;
}
void Person::FormalShow() const
{
cout << "lastname firstname foramt\n";
cout << "Name: " << lname << " " << fname << endl;
}
exercise02.cpp
#include<iostream>
#include"Person.h"
using namespace std;