知迩

实验5 继承和多态

 

实验任务3

 1 #ifndef PETS_HPP
 2 #define PETS_HPP
 3 
 4 #include <string>
 5 #include <iostream>
 6 
 7 class MachinePets {
 8 protected:
 9     std::string nickname;
10 
11 public:
12     MachinePets(const std::string &s) : nickname(s) {}
13 
14     std::string get_nickname() const {
15         return nickname;
16     }
17 
18     virtual ~MachinePets() {}
19 
20     virtual std::string talk() const = 0;
21 };
22 
23 class PetCats : public MachinePets {
24 public:
25     PetCats(const std::string &s) : MachinePets(s) {}
26 
27     std::string talk() const override {
28         return "miao wu~";
29     }
30 };
31 
32 class PetDogs : public MachinePets {
33 public:
34     PetDogs(const std::string &s) : MachinePets(s) {}
35 
36     std::string talk() const override {
37         return "wang wang~";
38     }
39 };
40 
41 #endif 
pets.hpp
 1 #include <iostream>
 2 #include <vector>
 3 #include "pets.hpp"
 4 
 5 void test() {
 6     using namespace std;
 7 
 8     vector<MachinePets *> pets;
 9 
10     pets.push_back(new PetCats("miku"));
11     pets.push_back(new PetDogs("da huang"));
12 
13     for(auto &ptr: pets)
14         cout <<ptr->get_nickname() << " says " << ptr->talk() << endl;
15 }
16 
17 int main() {
18     test();
19 }
task3.cpp

 

运行测试截图

 

实验任务4

 1 #ifndef FILM_HPP
 2 #define FILM_HPP
 3 
 4 #include <iostream>
 5 #include <string>
 6 #include <iomanip>
 7 #include <sstream>
 8 
 9 class Film {
10 private:
11     std::string title;
12     std::string director;
13     std::string country;
14     int year;
15 
16 public:
17     Film() : year(0) {} // 默认构造函数
18 
19     // 输入运算符重载
20     friend std::istream& operator>>(std::istream& is, Film& f);
21 
22     // 输出运算符重载
23     friend std::ostream& operator<<(std::ostream& os, const Film& f);
24     friend void readFilmWithPrompt(Film& f); 
25 
26     // 获取年份的辅助函数,用于排序
27     int getYear() const { return year; }
28 };
29 
30 // 辅助函数,用于从标准输入读取Film对象,并带有提示符
31 void readFilmWithPrompt(Film& f);
32 
33 // 比较函数,用于按年份排序
34 inline bool compare_by_year(const Film& a, const Film& b) {
35     return a.getYear() < b.getYear();
36 }
37 
38 // 输入运算符重载的定义
39 inline std::istream& operator>>(std::istream& is, Film& f) {
40     readFilmWithPrompt(f);
41     return is;
42 }
43 
44 // 输出运算符重载的定义
45 inline std::ostream& operator<<(std::ostream& os, const Film& f) {
46     std::ostringstream oss;
47     oss << std::setfill(' ');  // 设置填充字符为空格
48     oss            // 直接输出标签,不加宽度设置
49         << std::setw(17) << f.title                                      
50         << std::setw(18) << f.director                                   
51         << std::setw(16) << f.country                                  
52         << std::setw(8) << f.year;  
53     return os << oss.str();
54 }
55 
56 // 辅助函数的定义,带有提示符读取Film对象
57 inline void readFilmWithPrompt(Film& f) {
58     std::string input;
59     std::cout << "录入片名:";
60     std::getline(std::cin, input);
61     f.title = input;
62     
63     std::cout << "录入导演:";
64     std::getline(std::cin, input);
65     f.director = input;
66     
67     std::cout << "录入制片国家/地区: ";
68     std::getline(std::cin, input);
69     f.country = input;
70     
71     std::cout << "录入上映年份: ";
72     std::getline(std::cin, input);
73     f.year = std::stoi(input);  
74 }
75 
76 #endif // FILM_HPP
film.hpp
 1 #include "film.hpp"
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 #include <algorithm>
 6 void test() {
 7    using namespace std;
 8    
 9    int n;
10    cout << "输入电影数目: ";
11    cin >> n;
12    cin.ignore(numeric_limits<streamsize>::max(), '\n');
13    cout << "录入" << n << "部影片信息" << endl;
14    vector<Film> film_lst;
15    for(int i = 0; i < n; ++i) {
16        Film f;
17        cout << string(20, '-') << "" << i+1 << "部影片录入" << string(20,
18 '-') << endl;
19        cin >> f;
20        film_lst.push_back(f);
21   }
22    // 按发行年份升序排序
23    sort(film_lst.begin(), film_lst.end(), compare_by_year);
24    cout << string(20, '=') + "电影信息(按发行年份)" +  string(20, '=')<< endl;
25    for(auto &f: film_lst)
26        cout << f << endl;
27 }
28 int main() {
29    test();
30 }
task4.cpp

 

运行测试截图

 

实验任务5

 1 #ifndef COMPLEX_HPP
 2 #define COMPLEX_HPP
 3 
 4 #include <iostream>
 5 #include <iomanip>
 6 #include <limits> // 用于 std::numeric_limits
 7 
 8 template <typename T>
 9 class Complex {
10 private:
11     T real;
12     T imag;
13 
14 public:
15     // 构造函数
16     Complex(T r = 0, T i = 0) : real(r), imag(i) {}
17 
18     // 获取实部和虚部
19     T get_real() const { return real; }
20     T get_imag() const { return imag; }
21 
22     // 重载 += 运算符
23     Complex& operator+=(const Complex& other) {
24         real += other.real;
25         imag += other.imag;
26         return *this;
27     }
28 
29     // 重载 + 运算符
30     Complex operator+(const Complex& other) const {
31         return Complex(real + other.real, imag + other.imag);
32     }
33 
34     // 重载 == 运算符
35     bool operator==(const Complex& other) const {
36         return real == other.real && imag == other.imag;
37     }
38 
39     // 重载 << 运算符用于输出流
40     friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
41         os << c.real;
42         if (c.imag >= 0) {
43             os << " + " << c.imag << "i";
44         } else {
45             os << " - " << -c.imag << "i";
46         }
47         return os;
48     }
49 
50     friend std::istream& operator>>(std::istream& is, Complex& c) {
51         is >> c.real  >> c.imag; // 读取实部和虚部,中间用一个空格分隔
52 
53         return is;
54     }
55 
56 };
57 
58 #endif // COMPLEX_HPP
Complex.hpp
 1 #include "Complex.hpp"
 2 #include <iostream>
 3 
 4 using std::cin;
 5 using std::cout;
 6 using std::endl;
 7 using std::boolalpha;
 8 
 9 void test1() {
10     Complex<int> c1(2, -5), c2(c1);
11 
12     cout << "c1 = " << c1 << endl;
13     cout << "c2 = " << c2 << endl;
14     cout << "c1 + c2 = " << c1 + c2 << endl;
15     
16     c1 += c2;
17     cout << "c1 = " << c1 << endl;
18     cout << boolalpha << (c1 == c2) << endl;
19 }
20 
21 void test2() {
22     Complex<double> c1, c2;
23     cout << "Enter c1 and c2: ";
24     cin >> c1 >> c2;
25     cout << "c1 = " << c1 << endl;
26     cout << "c2 = " << c2 << endl;
27 
28     cout << "c1.real = " << c1.get_real() << endl;
29     cout << "c1.imag = " << c1.get_imag() << endl;
30 }
31 
32 int main() {
33     cout << "自定义类模板Complex测试1: " << endl;
34     test1();
35 
36     cout << endl;
37 
38     cout << "自定义类模板Complex测试2: " << endl;
39     test2();
40 }
task5.cpp

 

运行测试截图

 

实验任务6

 1 //date.h
 2 #ifndef __DATE_H__
 3 #define __DATE_H__
 4 
 5 class Date {    //日期类
 6 private:
 7     int year;        //
 8     int month;        //
 9     int day;        //
10     int totalDays;    //该日期是从公元元年1月1日开始的第几天
11 
12 public:
13     Date(int year, int month, int day);    //用年、月、日构造日期
14     int getYear() const { return year; }
15     int getMonth() const { return month; }
16     int getDay() const { return day; }
17     int getMaxDay() const;        //获得当月有多少天
18     bool isLeapYear() const {    //判断当年是否为闰年
19         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
20     }
21     void show() const;            //输出当前日期
22     //计算两个日期之间差多少天    
23     int operator - (const Date& date) const {
24         return totalDays - date.totalDays;
25     }
26 };
27 
28 #endif //__DATE_H__
date.h
 1 //date.cpp
 2 #include "date.h"
 3 #include <iostream>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 namespace {    //namespace使下面的定义只在当前文件中有效
 8     //存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
 9     const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
10 }
11 
12 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
13     if (day <= 0 || day > getMaxDay()) {
14         cout << "Invalid date: ";
15         show();
16         cout << endl;
17         exit(1);
18     }
19     int years = year - 1;
20     totalDays = years * 365 + years / 4 - years / 100 + years / 400
21         + DAYS_BEFORE_MONTH[month - 1] + day;
22     if (isLeapYear() && month > 2) totalDays++;
23 }
24 
25 int Date::getMaxDay() const {
26     if (isLeapYear() && month == 2)
27         return 29;
28     else
29         return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
30 }
31 
32 void Date::show() const {
33     cout << getYear() << "-" << getMonth() << "-" << getDay();
34 }
date.cpp
 1 //accumulator.h
 2 #ifndef __ACCUMULATOR_H__
 3 #define __ACCUMULATOR_H__
 4 #include "date.h"
 5 
 6 class Accumulator {    //将某个数值按日累加
 7 private:
 8     Date lastDate;    //上次变更数值的时期
 9     double value;    //数值的当前值
10     double sum;        //数值按日累加之和
11 public:
12     //构造函数,date为开始累加的日期,value为初始值
13     Accumulator(const Date &date, double value)
14         : lastDate(date), value(value), sum(0) { }
15 
16     //获得到日期date的累加结果
17     double getSum(const Date &date) const {
18         return sum + value * (date - lastDate);
19     }
20 
21     //在date将数值变更为value
22     void change(const Date &date, double value) {
23         sum = getSum(date);
24         lastDate = date;
25         this->value = value;
26     }
27 
28     //初始化,将日期变为date,数值变为value,累加器清零
29     void reset(const Date &date, double value) {
30         lastDate = date;
31         this->value = value;
32         sum = 0;
33     }
34 };
35 
36 #endif //__ACCUMULATOR_H__
accumulator.h
 1 //account.h
 2 #ifndef __ACCOUNT_H__
 3 #define __ACCOUNT_H__
 4 #include "date.h"
 5 #include "accumulator.h"
 6 #include <string>
 7 
 8 class Account { //账户类
 9 private:
10     std::string id;    //帐号
11     double balance;    //余额
12     static double total; //所有账户的总金额
13 protected:
14     //供派生类调用的构造函数,id为账户
15     Account(const Date &date, const std::string &id);
16     //记录一笔帐,date为日期,amount为金额,desc为说明
17     void record(const Date &date, double amount, const std::string &desc);
18     //报告错误信息
19     void error(const std::string &msg) const;
20 public:
21     const std::string &getId() const { return id; }
22     double getBalance() const { return balance; }
23     static double getTotal() { return total; }
24     //存入现金,date为日期,amount为金额,desc为款项说明
25     virtual void deposit(const Date &date, double amount, const std::string &desc) = 0;
26     //取出现金,date为日期,amount为金额,desc为款项说明
27     virtual void withdraw(const Date &date, double amount, const std::string &desc) = 0;
28     //结算(计算利息、年费等),每月结算一次,date为结算日期
29     virtual void settle(const Date &date) = 0;
30     //显示账户信息
31     virtual void show() const;
32 };
33 
34 class SavingsAccount : public Account { //储蓄账户类
35 private:
36     Accumulator acc;    //辅助计算利息的累加器
37     double rate;        //存款的年利率
38 public:
39     //构造函数
40     SavingsAccount(const Date &date, const std::string &id, double rate);
41     double getRate() const { return rate; }
42     virtual void deposit(const Date &date, double amount, const std::string &desc);
43     virtual void withdraw(const Date &date, double amount, const std::string &desc);
44     virtual void settle(const Date &date);
45 };
46 
47 class CreditAccount : public Account { //信用账户类
48 private:
49     Accumulator acc;    //辅助计算利息的累加器
50     double credit;        //信用额度
51     double rate;        //欠款的日利率
52     double fee;            //信用卡年费
53 
54     double getDebt() const {    //获得欠款额
55         double balance = getBalance();
56         return (balance < 0 ? balance : 0);
57     }
58 public:
59     //构造函数
60     CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
61     double getCredit() const { return credit; }
62     double getRate() const { return rate; }
63     double getFee() const { return fee; }
64     double getAvailableCredit() const {    //获得可用信用
65         if (getBalance() < 0) 
66             return credit + getBalance();
67         else
68             return credit;
69     }
70     virtual void deposit(const Date &date, double amount, const std::string &desc);
71     virtual void withdraw(const Date &date, double amount, const std::string &desc);
72     virtual void settle(const Date &date);
73     virtual void show() const;
74 };
75 
76 #endif //__ACCOUNT_H__
account.h
 1 //account.cpp
 2 #include "account.h"
 3 #include <cmath>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 double Account::total = 0;
 8 
 9 //Account类的实现
10 Account::Account(const Date &date, const string &id)
11     : id(id), balance(0) {
12     date.show();
13     cout << "\t#" << id << " created" << endl;
14 }
15 
16 void Account::record(const Date &date, double amount, const string &desc) {
17     amount = floor(amount * 100 + 0.5) / 100;    //保留小数点后两位
18     balance += amount;
19     total += amount;
20     date.show();
21     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
22 }
23 
24 void Account::show() const {
25     cout << id << "\tBalance: " << balance;
26 }
27 
28 void Account::error(const string &msg) const {
29     cout << "Error(#" << id << "): " << msg << endl;
30 }
31 
32 //SavingsAccount类相关成员函数的实现
33 SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
34     : Account(date, id), rate(rate), acc(date, 0) { }
35 
36 void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
37     record(date, amount, desc);
38     acc.change(date, getBalance());
39 }
40 
41 void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
42     if (amount > getBalance()) {
43         error("not enough money");
44     } else {
45         record(date, -amount, desc);
46         acc.change(date, getBalance());
47     }
48 }
49 
50 void SavingsAccount::settle(const Date &date) {
51     if (date.getMonth() == 1) {    //每年的一月计算一次利息
52         double interest = acc.getSum(date) * rate
53             / (date - Date(date.getYear() - 1, 1, 1));
54         if (interest != 0)
55             record(date, interest, "interest");
56         acc.reset(date, getBalance());
57     }
58 }
59 
60 //CreditAccount类相关成员函数的实现
61 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
62     : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }
63 
64 void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
65     record(date, amount, desc);
66     acc.change(date, getDebt());
67 }
68 
69 void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
70     if (amount - getBalance() > credit) {
71         error("not enough credit");
72     } else {
73         record(date, -amount, desc);
74         acc.change(date, getDebt());
75     }
76 }
77 
78 void CreditAccount::settle(const Date &date) {
79     double interest = acc.getSum(date) * rate;
80     if (interest != 0)
81         record(date, interest, "interest");
82     if (date.getMonth() == 1)
83         record(date, -fee, "annual fee");
84     acc.reset(date, getDebt());
85 }
86 
87 void CreditAccount::show() const {
88     Account::show();
89     cout << "\tAvailable credit:" << getAvailableCredit();
90 }
account.cpp
 1 //8_8.cpp
 2 #include "account.h"
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int main() {
 7     Date date(2008, 11, 1);    //起始日期
 8     //建立几个账户
 9     SavingsAccount sa1(date, "S3755217", 0.015);
10     SavingsAccount sa2(date, "02342342", 0.015);
11     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
12     Account *accounts[] = { &sa1, &sa2, &ca };
13     const int n = sizeof(accounts) / sizeof(Account*);    //账户总数
14 
15     cout << "(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
16     char cmd;
17     do {
18         //显示日期和总金额
19         date.show();
20         cout << "\tTotal: " << Account::getTotal() << "\tcommand> ";
21 
22         int index, day;
23         double amount;
24         string desc;
25 
26         cin >> cmd;
27         switch (cmd) {
28         case 'd':    //存入现金
29             cin >> index >> amount;
30             getline(cin, desc);
31             accounts[index]->deposit(date, amount, desc);
32             break;
33         case 'w':    //取出现金
34             cin >> index >> amount;
35             getline(cin, desc);
36             accounts[index]->withdraw(date, amount, desc);
37             break;
38         case 's':    //查询各账户信息
39             for (int i = 0; i < n; i++) {
40                 cout << "[" << i << "] ";
41                 accounts[i]->show();
42                 cout << endl;
43             }
44             break;
45         case 'c':    //改变日期
46             cin >> day;
47             if (day < date.getDay())
48                 cout << "You cannot specify a previous day";
49             else if (day > date.getMaxDay())
50                 cout << "Invalid day";
51             else
52                 date = Date(date.getYear(), date.getMonth(), day);
53             break;
54         case 'n':    //进入下个月
55             if (date.getMonth() == 12)
56                 date = Date(date.getYear() + 1, 1, 1);
57             else
58                 date = Date(date.getYear(), date.getMonth() + 1, 1);
59             for (int i = 0; i < n; i++)
60                 accounts[i]->settle(date);
61             break;
62         }
63     } while (cmd != 'e');
64     return 0;
65 }
8_8.cpp

 

运行测试截图

 

posted on 2024-12-08 10:36  知迩  阅读(3)  评论(0编辑  收藏  举报

导航