C++ Prime Plus 第6版 第10章编程练习解析以及运行结果
1. 第1题
//Account.h
#include<string>
class Account
{
private:
std::string company_name;//储户姓名
std::string account;//账户
double money;//存款
public:
void Create(std::string name,std::string a,double m);//创建一个对象
void Show() const;
void Saving(double m);
void Withdraw(double m);
};
//Account.cpp
#include "Account.h"
#include<iostream>
#include<string>
void Account::Create(std::string name, std::string a, double m)
{
company_name = name;
account = a;
money = m;
}
void Account::Show() const
{
std::cout << "储户名称:" << company_name << std::endl;
std::cout << "账号:" << account << std::endl;
std::cout << "存款:" << money << std::endl;
}
void Account::Saving(double m)
{
if (m < 0)
{
std::cout << "存款金额不能为负数!" << std::endl;
}
else
{
std::cout << "存入:" << m << std::endl;
money += m;
}
}
void Account::Withdraw(double m)
{
if (m > money)
{
std::cout << "账内余额不足!" << std::endl;
}
else
{
std::cout << "取出:" << m << std::endl;
money -= m;
}
}
#include<iostream>
#include"Account.h"
using namespace std;
int main()
{
Account a1;
a1.Create("ICBC", "1234567890", 0);
a1.Show();
a1.Saving(5000);
a1.Show();
a1.Withdraw(4000);
a1.Show();
return 0;
}
运行结果:
2. 第2题
//Person.h
#include <string>
using namespace std;
class Person
{
private:
static const int LIMIT = 25;
string lname;//lastname
char fname[LIMIT];//firstname
public:
Person() { lname = ""; fname[0] = '\0'; }//#1
Person(const string & ln, const char *fn = "Heyyou");//#2
void Show()const;//格式:firstname lastname
void FormalShow()const;//格式:lastname,firstname
~Person();
};
//Person.cpp
#include "Person.h"
#include<iostream>
#include<cstring>
Person::Person(const string & ln, const char *fn )
{
lname = ln;
strcpy_s(fname, fn);
}
//格式:firstname lastname
void Person::Show()const
{
cout << "Fullname:" << fname << " " << lname << endl;
}
//格式:lastname,firstname
void Person::FormalShow()const
{
cout << "Fullname:" << lname << "," << fname << endl;
}
Person::~Person()
{
}
#include<iostream>
#include"Person.h"
using namespace std;
int main()
{
Person one;
one.Show();
one.FormalShow();
Person two("Smythecraft");
two.Show();
two.FormalShow();
Person three("Dimwiddy", "Sam");
three.Show();
three.FormalShow();
return 0;
}
运行结果:
–下次更新–