实验5 继承和多态

news/2024/12/2 20:02:07/文章来源:https://www.cnblogs.com/yrx0415/p/18582585

实验任务三

源码

 1 #pragma once
 2 #include<iostream>
 3 #include<string>
 4 
 5 using std::string;
 6 using std::cout;
 7 using std::endl;
 8 
 9 //电子宠物类
10 class MachinePets {
11 private:
12     string nickname;
13 public:
14     MachinePets(const string&s="");
15     string get_nickname() const;
16     virtual string talk()=0;
17 };
18 
19 MachinePets::MachinePets(const string& s) :nickname{ s } {
20 
21 }
22 
23 string MachinePets::get_nickname() const {
24     return nickname;
25 }
26 
27 //猫类
28 class PetCats :public MachinePets {
29 public:
30     PetCats(const string& s = "");
31     string talk();
32 };
33 
34 PetCats::PetCats(const string& s) :MachinePets{ s } {
35     
36 }
37 
38 string PetCats::talk() {
39     return "miao wu~";
40 }
41 
42 //狗类
43 class PetDogs :public MachinePets {
44 public:
45     PetDogs(const string& s = "");
46     string talk();
47 };
48 
49 PetDogs::PetDogs(const string& s) :MachinePets{ s } {
50 
51 }
52 
53 string PetDogs::talk() {
54     return "wang wang~";
55 }
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

运行结果

 

 

 

实验任务四

源码

 1 #pragma once
 2 #include<iostream>
 3 #include<string>
 4 #include<iomanip>
 5 
 6 using std::string;
 7 using std::cout;
 8 using std::endl;
 9 using std::setw;
10 
11 class Film {
12 private:
13     string title;
14     string director;
15     string country;
16     int year;
17 public:
18     Film():title(""),director(""),country(""),year(0){}
19     Film(const string&t,const string&d,const string c,const int y)
20         :title(t),director(d),country(c),year(y){}
21 
22     friend std::istream& operator>>(std::istream &is, Film& film);
23     friend std::ostream& operator<<(std::ostream &os, Film& film);
24 
25     int getyear()const;
26 
27 };
28 
29 std::istream& operator>>(std::istream &is, Film& film){
30     cout << "录入片名:"; 
31     is >> film.title;
32     cout << "录入导演:"; 
33     is >> film.director;
34     cout << "录入制片国家/地区:"; 
35     is >> film.country;
36     cout << "录入上映年份:"; 
37     is >> film.year; 
38     return is;
39 }
40 
41 std::ostream& operator<<(std::ostream &os, Film& film) {
42     os << std::left;
43     os << setw(15) << film.title
44         << setw(15) << film.director
45         << setw(15) << film.country 
46         << setw(15) << film.year<<endl;
47     return os;
48 }
49 
50 int Film::getyear() const{
51     return year;
52 }
53 
54 bool compare_by_year(const Film& a, const Film& b) {
55     return a.getyear() < b.getyear();
56 }
film.hpp
 1 #include "film.hpp"
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 #include <algorithm>
 6 
 7 void test() {
 8     using namespace std;
 9 
10     int n;
11     cout << "输入电影数目: ";
12     cin >> n;
13 
14     cout << "录入" << n << "部影片信息" << endl;
15     vector<Film> film_lst;
16     for (int i = 0; i < n; ++i) {
17         Film f;
18         cout << string(20, '-') << "" << i + 1 << "部影片录入" << string(20, '-') << endl;
19         cin >> f;
20         film_lst.push_back(f);
21     }
22 
23     // 按发行年份升序排序
24     sort(film_lst.begin(), film_lst.end(), compare_by_year);
25 
26     cout << string(20, '=') + "电影信息(按发行年份)" + string(20, '=') << endl;
27     for (auto& f : film_lst)
28         cout << f << endl;
29 }
30 
31 int main() {
32     test();
33 }
task4.cpp

运行结果

 

 

 

实验任务五

源码

 1 #pragma once
 2 
 3 #include <iostream>
 4 
 5 template <typename T>
 6 class Complex {
 7 private:
 8     T real;  // 实部
 9     T imag;  // 虚部
10 
11 public:
12     // 默认构造函数
13     Complex(T r = 0, T i = 0) : real(r), imag(i) {}
14 
15     // 拷贝构造函数
16     Complex(const Complex& other) : real(other.real), imag(other.imag) {}
17 
18     // 获取实部
19     T get_real() const { return real; }
20 
21     // 获取虚部
22     T get_imag() const { return imag; }
23 
24     // 重载+运算符
25     Complex operator+(const Complex& other) const {
26         return Complex(real + other.real, imag + other.imag);
27     }
28 
29     // 重载+=运算符
30     Complex& operator+=(const Complex& other) {
31         real += other.real;
32         imag += other.imag;
33         return *this;
34     }
35 
36     // 重载==运算符
37     bool operator==(const Complex& other) const {
38         return real == other.real && imag == other.imag;
39     }
40 
41     // 重载输入流运算符
42     friend std::istream& operator>>(std::istream& in, Complex& c) {
43         in >> c.real >> c.imag;
44         return in;
45     }
46 
47     // 重载输出流运算符
48     friend std::ostream& operator<<(std::ostream& out, const Complex& c) {
49         out << c.real << (c.imag >= 0 ? " + " : " - ") << std::abs(c.imag) << "i";
50         return out;
51     }
52 };
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

运行结果

 

 

 

实验任务六

源码

 1 #pragma once
 2 
 3 class Date {
 4 private:
 5     int year;
 6     int month;
 7     int day;
 8     int totalDays;
 9 
10 public:
11     Date(int year, int month, int day);
12     int getYear() const { return year; }
13     int getMonth() const { return month; }
14     int getDay() const { return day; }
15     int getMaxDay() const;
16     bool isLeapYear() const {
17         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
18     }
19     void show() const;
20     int operator-(const Date& date) const {
21         return totalDays - date.totalDays;
22     }
23 };
date.h
 1 #include "date.h"
 2 #include <iostream>
 3 #include <cstdlib>
 4 using namespace std;
 5 
 6 namespace {
 7     const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
 8 }
 9 
10 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
11     if (day <= 0 || day > getMaxDay()) {
12         cout << "Invalid date: ";
13         show();
14         cout << endl;
15         exit(1);
16     }
17     int years = year - 1;
18     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
19     if (isLeapYear() && month > 2) totalDays++;
20 }
21 
22 int Date::getMaxDay() const {
23     if (isLeapYear() && month == 2)
24         return 29;
25     else return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
26 }
27 
28 void Date::show() const {
29     cout << getYear() << "-" << getMonth() << "-" << getDay();
30 }
date.cpp
 1 #pragma once
 2 #include "date.h"
 3 
 4 class Accumulator {
 5 private:
 6     Date lastDate;
 7     double value;
 8     double sum;
 9 
10 public:
11     Accumulator(const Date& date, double value) : lastDate(date), value(value), sum{ 0 } {}
12 
13     double getSum(const Date& date) const {
14         return sum + value * (date - lastDate);
15     }
16 
17     void change(const Date& date, double value) {
18         sum = getSum(date);
19         lastDate = date;
20         this->value = value;
21     }
22 
23     void reset(const Date& date, double value) {
24         lastDate = date;
25         this->value = value;
26         sum = 0;
27     }
28 };
accumulator.h
 1 #pragma once
 2 #include "date.h"
 3 #include "accumulator.h"
 4 #include <string>
 5 using namespace std;
 6 
 7 class Account {
 8 private:
 9     string id;
10     double balance;
11     static double total;
12 protected:
13     Account(const Date& date, const string& id);
14     void record(const Date& date, double amount, const string& desc);
15     void error(const string& msg) const;
16 public:
17     const string& getId() { return id; }
18     double getBalance() const { return balance; }
19     static double getTotal() { return total; }
20     virtual void deposit(const Date& date, double amount, const string& desc) = 0;
21     virtual void withdraw(const Date& date, double amount, const string& desc) = 0;
22     virtual void settle(const Date& date) = 0;
23     virtual void show() const;
24 };
25 
26 class SavingsAccount : public Account {
27 private:
28     Accumulator acc;
29     double rate;
30 public:
31     SavingsAccount(const Date& date, const string& id, double rate);
32     double getRate() const { return rate; }
33     void deposit(const Date& date, double amount, const string& desc);
34     void withdraw(const Date& date, double amount, const string& desc);
35     void settle(const Date& date);
36 };
37 
38 class CreditAccount : public Account {
39 private:
40     Accumulator acc;
41     double credit;
42     double rate;
43     double fee;
44     double getDebt() const {
45         double balance = getBalance();
46         return (balance < 0 ? balance : 0);
47     }
48 public:
49     CreditAccount(const Date& date, const string& id, double credit, double rate, double fee);
50     double getCredit() const { return credit; }
51     double getRate() const { return rate; }
52     double getFee() const { return fee; }
53     double getAvailableCredit() const {
54         if (getBalance() < 0) return credit + getBalance();
55         else return credit;
56     }
57     void deposit(const Date& date, double amount, const string& desc);
58     void withdraw(const Date& date, double amount, const string& desc);
59     void settle(const Date& date);
60     void show() const;
61 };
account.h
 1 #include "account.h"
 2 #include <cmath>
 3 #include<iostream>
 4 using namespace std;
 5 
 6 double Account::total = 0;
 7 
 8 Account::Account(const Date& date, const string& id) : id(id), balance(0) {
 9     date.show();
10     cout << "\t#" << id << " created" << endl;
11 }
12 
13 void Account::record(const Date& date, double amount, const string& desc) {
14     amount = floor(amount * 100 + 0.5) / 100;
15     balance += amount;
16     total += amount;
17     date.show();
18     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
19 }
20 
21 void Account::show() const {
22     cout << id << "\tBalance: " << balance;
23 }
24 
25 void Account::error(const string& msg) const {
26     cout << "Error (#" << id << "): " << msg << endl;
27 }
28 
29 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate)
30     : Account(date, id), rate(rate), acc(date, 0) {}
31 
32 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
33     record(date, amount, desc);
34     acc.change(date, getBalance());
35 }
36 
37 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
38     if (amount > getBalance()) {
39         error("not enough money");
40     }
41     else {
42         record(date, -amount, desc);
43         acc.change(date, getBalance());
44     }
45 }
46 
47 void SavingsAccount::settle(const Date& date) {
48     double interest = acc.getSum(date) * rate / (date - Date(date.getYear() - 1, 1, 1));
49     if (interest != 0) record(date, interest, "interest");
50     acc.reset(date, getBalance());
51 }
52 
53 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
54     : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {}
55 
56 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
57     record(date, amount, desc);
58     acc.change(date, getDebt());
59 }
60 
61 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
62     if (amount - getBalance() > credit) {
63         error("not enough credit");
64     }
65     else {
66         record(date, -amount, desc);
67         acc.change(date, getDebt());
68     }
69 }
70 
71 void CreditAccount::settle(const Date& date) {
72     double interest = acc.getSum(date) * rate;
73     if (interest != 0) record(date, interest, "interest");
74     if (date.getMonth() == 1) record(date, -fee, "annual fee");
75     acc.reset(date, getDebt());
76 }
77 
78 void CreditAccount::show() const {
79     Account::show();
80     cout << "\tAvailable credit: " << getAvailableCredit();
81 }
account.cpp
 1 #include "account.h"
 2 #include<iostream>
 3 using namespace std;
 4 
 5 int main() {
 6     Date date(2008, 11, 1);
 7     SavingsAccount sa1(date, "S3755217", 0.015);
 8     SavingsAccount sa2(date, "02342342", 0.015);
 9     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
10     Account* accounts[] = { &sa1, &sa2, &ca };
11     const int n = sizeof(accounts) / sizeof(Account*);
12     cout << "(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
13     char cmd;
14     do {
15         date.show();
16         cout << "\tTotal:" << Account::getTotal() << "\tcommand>";
17         int index, day;
18         double amount;
19         string desc;
20         cin >> cmd;
21         switch (cmd) {
22         case 'd':
23             cin >> index >> amount;
24             getline(cin, desc);
25             accounts[index]->deposit(date, amount, desc);
26             break;
27         case 'w':
28             cin >> index >> amount;
29             getline(cin, desc);
30             accounts[index]->withdraw(date, amount, desc);
31             break;
32         case 's':
33             for (int i = 0; i < n; i++) {
34                 cout << "[" << i << "]";
35                 accounts[i]->show();
36                 cout << endl;
37             }
38             break;
39         case 'c':
40             cin >> day;
41             if (day < date.getDay()) {
42                 cout << "You cannot specify a previous day";
43             }
44             else if (day > date.getMaxDay())
45                 cout << "Invalid day";
46             else date = Date(date.getYear(), date.getMonth(), day);
47             break;
48         case 'n':
49             if (date.getMonth() == 12)
50                 date = Date(date.getYear() + 1, 1, 1);
51             else date = Date(date.getYear(), date.getMonth() + 1, 1);
52             for (int i = 0; i < n; i++) {
53                 accounts[i]->settle(date);
54             }
55             break;
56         }
57     } while (cmd != 'e');
58     return 0;
59 }
task6.cpp

运行结果

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/845597.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

idea创建web项目并连接数据库

1.在idea中连接数据库在连接的数据库中,可以写SQL语句,创建数据库、表等。 2.我的项目结构---学生请假系统Dao层:写一个学生实体类 Servlet层:业务层具体的怎么实现相关操作 1)最开始加上这个之后就不用配置映射文件了 2)然后是这个就不用另外的建立连接了 3)在resouces…

chrome 替换network中的返回内容,用以跨步调试

在开发调试中,有时候,某个接口,或者文件返回内容有问题,但线上的文件没问题。这时候就可以通过更改network中返回内容来实现跨步调试了。 test.html<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta n…

天梯赛 L2-004 这是二叉搜索树吗? 数据结构

反思:使用指针前先分配内存。#include<bits/stdc++.h> using namespace std; typedef struct node {int data;struct node* left;struct node* right; }*T; queue<int>q1; queue<int>q2; queue<int>q3; T result; void built1(T &t,int x) {if(t=…

Qt nativeEvent 不触发/不执行/无效

在做触摸屏项目的时候,各种控件都需要实现监听/触发点击事件,通常是通过信号/槽、事件过滤器(eventFilter)、重写mousePressEvent。 发现在QSpinBox中点击编辑框时不会触发任何鼠标相关点击事件。查资料发现通过重写nativeEvent函数可以拿到鼠标相关事件,不过有一个坑需要注…

testnet 资产管理系统 侦察|扫描|信息收集|网络空间搜索

TestNet简介 TestNet资产管理系统旨在提供全面、高效的互联网资产管理与监控服务,构建详细的资产信息库。 该系统能够帮助企业安全团队或渗透测试人员对目标资产进行深入侦察和分析,提供攻击者视角的持续风险监测,协助用户实时掌握资产动态,识别并修复安全漏洞,从而有效收…

记录---前端实现画中画超简单,让网页飞出浏览器

🧑‍💻 写在开头 点赞 + 收藏 === 学会🤣🤣🤣Document Picture-in-Picture 介绍今天,我来介绍一个非常酷的前端功能:文档画中画 (Document Picture-in-Picture, 本文简称 PiP)。你有没有想过,网页上的任何内容能悬浮在桌面上?😏 🎬 视频流媒体的画中画功能你…

洛谷题单指南-线段树-P4513 小白逛公园

原题链接:https://www.luogu.com.cn/problem/P4513 题意解读:给定序列a[n],支持两种操作:1.查询区间[l,r]内的最大子段和 2.将a[x]修改成s,输出其中每一个查询操作的结果。 解题思路:区间问题依然想到线段树,问题主要在于线段树的节点要维护哪些信息: 最直接的,肯定要…

LeetCode 2413[最小偶倍数]

LeetCode 2413[最小偶倍数]题目 链接 LeetCode 2413[最小偶倍数] 详情实例提示题解 思路 判断奇偶性 奇数乘以2并返回 偶数直接返回 代码 class Solution { public:int smallestEvenMultiple(int n) {if (0 == (n % 2))return n;return 2 * n;} };本文来自博客园,作者:EricsT…

power BI

工作一:实现地图 1、先启用地图功能2、导入数据 获取数据更改数据类型检测:加载出现在右侧

使用服务器docker搭建Pwn题目

一、docker的安装 1、安装前先卸载操作系统默认安装的docker sudo apt-get remove docker docker-engine docker.io containerd runc 2、安装必要支持 sudo apt install apt-transport-https ca-certificates curl software-properties-common gnupg lsb-release 3、添加gpg KE…

Windows系统下通过命令行获取进程指标

1.获取当前ProcessID。GetCurrentProcess2.执行cmd或PowerShell cmd:wmic process where "processid=15844" get /format:list PowerShell:Get-Process -id 15844 | Format-List * 作者:快雪 出处:http://www.cnblogs.com/kuaixue/ 本文版权归作者所有,欢迎转…

各层协议

原文链接:点我