实验5 多态

news/2025/12/10 8:46:00/文章来源:https://www.cnblogs.com/zijuan0605/p/19329237

一、实验任务1

源代码task1

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 // 发行/出版物类:Publisher (抽象类)
 6 class Publisher {
 7 public:
 8     Publisher(const std::string &name_ = "");            // 构造函数
 9     virtual ~Publisher() = default;
10 
11 public:
12     virtual void publish() const = 0;                 // 纯虚函数,作为接口继承
13     virtual void use() const = 0;                     // 纯虚函数,作为接口继承
14 
15 protected:
16     std::string name;    // 发行/出版物名称
17 };
18 
19 // 图书类: Book
20 class Book: public Publisher {
21 public:
22     Book(const std::string &name_ = "", const std::string &author_ = "");  // 构造函数
23 
24 public:
25     void publish() const override;        // 接口
26     void use() const override;            // 接口
27 
28 private:
29     std::string author;          // 作者
30 };
31 
32 // 电影类: Film
33 class Film: public Publisher {
34 public:
35     Film(const std::string &name_ = "", const std::string &director_ = "");   // 构造函数
36 
37 public:
38     void publish() const override;    // 接口
39     void use() const override;        // 接口            
40 
41 private:
42     std::string director;        // 导演
43 };
44 
45 
46 // 音乐类:Music
47 class Music: public Publisher {
48 public:
49     Music(const std::string &name_ = "", const std::string &artist_ = "");
50 
51 public:
52     void publish() const override;        // 接口
53     void use() const override;            // 接口
54 
55 private:
56     std::string artist;      // 音乐艺术家名称
57 };
publisher.hpp
 1 #include <iostream>
 2 #include <string>
 3 #include "publisher.hpp"
 4 
 5 // Publisher类:实现
 6 Publisher::Publisher(const std::string &name_): name {name_} {
 7 }
 8 
 9 
10 // Book类: 实现
11 Book::Book(const std::string &name_ , const std::string &author_ ): Publisher{name_}, author{author_} {
12 }
13 
14 void Book::publish() const {
15     std::cout << "Publishing book《" << name << "》 by " << author << '\n';
16 }
17 
18 void Book::use() const {
19     std::cout << "Reading book 《" << name << "》 by " << author << '\n';
20 }
21 
22 
23 // Film类:实现
24 Film::Film(const std::string &name_, const std::string &director_):Publisher{name_},director{director_} {
25 }
26 
27 void Film::publish() const {
28     std::cout << "Publishing film <" << name << "> directed by " << director << '\n';
29 }
30 
31 void Film::use() const {
32     std::cout << "Watching film <" << name << "> directed by " << director << '\n';
33 }
34 
35 
36 // Music类:实现
37 Music::Music(const std::string &name_, const std::string &artist_): Publisher{name_}, artist{artist_} {
38 }
39 
40 void Music::publish() const {
41     std::cout << "Publishing music <" << name << "> by " << artist << '\n';
42 }
43 
44 void Music::use() const {
45     std::cout << "Listening to music <" << name << "> by " << artist << '\n';
46 }
publisher.cpp
 1 #include <memory>
 2 #include <iostream>
 3 #include <vector>
 4 #include "publisher.hpp"
 5 
 6 void test1() {
 7    std::vector<Publisher *> v;
 8 
 9    v.push_back(new Book("Harry Potter", "J.K. Rowling"));
10    v.push_back(new Film("The Godfather", "Francis Ford Coppola"));
11    v.push_back(new Music("Blowing in the wind", "Bob Dylan"));
12 
13    for(Publisher *ptr: v) {
14         ptr->publish();
15         ptr->use();
16         std::cout << '\n';
17         delete ptr;
18    }
19 }
20 
21 void test2() {
22     std::vector<std::unique_ptr<Publisher>> v;
23 
24     v.push_back(std::make_unique<Book>("Harry Potter", "J.K. Rowling"));
25     v.push_back(std::make_unique<Film>("The Godfather", "Francis Ford Coppola"));
26     v.push_back(std::make_unique<Music>("Blowing in the wind", "Bob Dylan"));
27 
28     for(const auto &ptr: v) {
29         ptr->publish();
30         ptr->use();
31         std::cout << '\n';
32     }
33 }
34 
35 void test3() {
36     Book book("A Philosophy of Software Design", "John Ousterhout");
37     book.publish();
38     book.use();
39 }
40 
41 int main() {
42     std::cout << "运行时多态:纯虚函数、抽象类\n";
43 
44     std::cout << "\n测试1: 使用原始指针\n";
45     test1();
46 
47     std::cout << "\n测试2: 使用智能指针\n";
48     test2();
49 
50     std::cout << "\n测试3: 直接使用类\n";
51     test3();
52 }
task1.cpp

运行结果截图

 

二、实验任务2

源代码task2

 1 #pragma once
 2 #include <string>
 3 
 4 // 图书描述信息类Book: 声明
 5 class Book {
 6 public:
 7     Book(const std::string &name_, 
 8          const std::string &author_, 
 9          const std::string &translator_, 
10          const std::string &isbn_, 
11          double price_);
12 
13     friend std::ostream& operator<<(std::ostream &out, const Book &book);
14 
15 private:
16     std::string name;        // 书名
17     std::string author;      // 作者
18     std::string translator;  // 译者
19     std::string isbn;        // isbn号
20     double price;        // 定价
21 };
book.hpp
 1 #include <iomanip>
 2 #include <iostream>
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 
 7 // 图书描述信息类Book: 实现
 8 Book::Book(const std::string &name_, 
 9           const std::string &author_, 
10           const std::string &translator_, 
11           const std::string &isbn_, 
12           double price_):name{name_}, author{author_}, translator{translator_}, isbn{isbn_}, price{price_} {
13 }
14 
15 // 运算符<<重载实现
16 std::ostream& operator<<(std::ostream &out, const Book &book) {
17     using std::left;
18     using std::setw;
19     
20     out << left;
21     out << setw(15) << "书名:" << book.name << '\n'
22         << setw(15) << "作者:" << book.author << '\n'
23         << setw(15) << "译者:" << book.translator << '\n'
24         << setw(15) << "ISBN:" << book.isbn << '\n'
25         << setw(15) << "定价:" << book.price;
26 
27     return out;
28 }
book.cpp
 1 #pragma once
 2 
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 // 图书销售记录类BookSales:声明
 7 class BookSale {
 8 public:
 9     BookSale(const Book &rb_, double sales_price_, int sales_amount_);
10     int get_amount() const;   // 返回销售数量
11     double get_revenue() const;   // 返回营收
12     
13     friend std::ostream& operator<<(std::ostream &out, const BookSale &item);
14 
15 private:
16     Book rb;         
17     double sales_price;      // 售价
18     int sales_amount;       // 销售数量
19 };
booksale.hpp
 1 #include <iomanip>
 2 #include <iostream>
 3 #include <string>
 4 #include "booksale.hpp"
 5 
 6 // 图书销售记录类BookSales:实现
 7 BookSale::BookSale(const Book &rb_, 
 8                    double sales_price_, 
 9                    int sales_amount_): rb{rb_}, sales_price{sales_price_}, sales_amount{sales_amount_} {
10 }
11 
12 int BookSale::get_amount() const {
13     return sales_amount;
14 }
15 
16 double BookSale::get_revenue() const {
17     return sales_amount * sales_price;
18 }
19 
20 // 运算符<<重载实现
21 std::ostream& operator<<(std::ostream &out, const BookSale &item) {
22     using std::left;
23     using std::setw;
24     
25     out << left;
26     out << item.rb << '\n'
27         << setw(15) << "售价:" << item.sales_price << '\n'
28         << setw(15) << "销售数量:" << item.sales_amount << '\n'
29         << setw(15) << "营收:" << item.get_revenue();
30 
31     return out;
32 }
booksale.cpp
 1 #include <algorithm>
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include "booksale.hpp"
 7 
 8 // 按图书销售数量比较
 9 bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
10     return x1.get_amount() > x2.get_amount();
11 }
12 
13 void test() {
14     using std::cin;
15     using std::cout;
16     using std::getline;
17     using std::sort;
18     using std::string;
19     using std::vector;
20     using std::ws;
21 
22     vector<BookSale> sales_records;         // 图书销售记录表
23 
24     int books_number;
25     cout << "录入图书数量: ";
26     cin >> books_number;
27 
28     cout << "录入图书销售记录\n";
29     for(int i = 0; i < books_number; ++i) {
30         string name, author, translator, isbn;
31         double price;
32         cout << string(20, '-') << "" << i+1 << "本图书信息录入" << string(20, '-') << '\n';
33         cout << "录入书名: "; getline(cin>>ws, name);
34         cout << "录入作者: "; getline(cin>>ws, author);
35         cout << "录入译者: "; getline(cin>>ws, translator);
36         cout << "录入isbn: "; getline(cin>>ws, isbn);
37         cout << "录入定价: "; cin >> price;
38 
39         Book book(name, author, translator, isbn, price);
40 
41         double sales_price;
42         int sales_amount;
43 
44         cout << "录入售价: "; cin >> sales_price;
45         cout << "录入销售数量: "; cin >> sales_amount;
46 
47         BookSale record(book, sales_price, sales_amount);
48         sales_records.push_back(record);
49     }
50 
51     // 按销售册数排序
52     sort(sales_records.begin(), sales_records.end(), compare_by_amount);
53 
54     // 按销售册数降序输出图书销售信息
55     cout << string(20, '=') <<  "图书销售统计" << string(20, '=') << '\n';
56     for(auto &record: sales_records) {
57         cout << record << '\n';
58         cout << string(40, '-') << '\n';
59     }
60 }
61 
62 int main() {
63     test();
64 }
task2.cpp

运行结果截图

087ac95cbe2ddf0e58f5af89107045cf

 

 

三、实验任务3

源代码task3

 1 #include <iostream>
 2 
 3 // 类A的定义
 4 class A {
 5 public:
 6     A(int x0, int y0);
 7     void display() const;
 8 
 9 private:
10     int x, y;
11 };
12 
13 A::A(int x0, int y0): x{x0}, y{y0} {
14 }
15 
16 void A::display() const {
17     std::cout << x << ", " << y << '\n';
18 }
19 
20 // 类B的定义
21 class B {
22 public:
23     B(double x0, double y0);
24     void display() const;
25 
26 private:
27     double x, y;
28 };
29 
30 B::B(double x0, double y0): x{x0}, y{y0} {
31 }
32 
33 void B::display() const {
34     std::cout << x << ", " << y << '\n';
35 }
36 
37 void test() {
38     std::cout << "测试类A: " << '\n';
39     A a(3, 4);
40     a.display();
41 
42     std::cout << "\n测试类B: " << '\n';
43     B b(3.2, 5.6);
44     b.display();
45 }
46 
47 int main() {
48     test();
49 }
task3_1.cpp
 1 #include <iostream>
 2 #include <string>
 3 
 4 // 定义类模板
 5 template<typename T>
 6 class X{
 7 public:
 8     X(T x0, T y0);
 9     void display();
10 
11 private:
12     T x, y;
13 };
14 
15 template<typename T>
16 X<T>::X(T x0, T y0): x{x0}, y{y0} {
17 }
18 
19 template<typename T>
20 void X<T>::display() {
21     std::cout << x << ", " << y << '\n';
22 }
23 
24 
25 void test() {
26     std::cout << "测试1: 用int实例化类模板X" << '\n';
27     X<int> x1(3, 4);
28     x1.display();
29 
30     std::cout << "\n测试2:用double实例化类模板X" << '\n';
31     X<double> x2(3.2, 5.6);
32     x2.display();
33 
34     std::cout << "\n测试3: 用string实例化类模板X" << '\n';
35     X<std::string> x3("hello", "oop");
36     x3.display();
37 }
38 
39 int main() {
40     test();
41 }
task3_2.cpp

 

四、实验任务4

 

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

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

相关文章

深南票据王

深南票据王深南票据王是一款便捷、易用、高效的票据打印软件,操作简单,方便易用。本软件可以记录各类收据、票据等销售数据,支持票据的新增、编辑、删除、保存、预览、打印等多种操作;软件支持用户管理、操作日志以…

2025年靠谱的安装楼梯升降椅公司推荐,老人爬楼专用楼梯升降 - 工业推荐榜

随着中国老龄化程度加深,让长者安全上下楼成为千万家庭的刚需。楼梯升降椅作为解决高龄家庭上下楼痛点的核心工具,市场需求持续增长,但如何选择靠谱的安装楼梯升降椅公司,却让许多家庭犯了难。以下依据专业度、安全…

智能家居用温度传感器有哪几种?哪种品牌性价比高值得选 - 工业品牌热点

工业测量领域中,温度传感器作为核心感知部件,是食品生产工艺稳定、智能家居环境调控、太阳能光伏效率优化的关键支撑。2024年数据显示,工业温度传感器市场规模超300亿元,年增速32%,但35%的投诉集中在极端工况稳定…

2025年口碑好的单极性脉冲电源厂家最新推荐权威榜 - 品牌宣传支持者

2025年口碑好的单极性脉冲电源厂家推荐权威榜行业背景与市场趋势随着工业自动化、新能源、半导体制造等领域的快速发展,单极性脉冲电源作为关键电子设备,市场需求持续增长。2024年全球单极性脉冲电源市场规模已达到5…

2025年精密轧机制造企业推荐:精密轧机生产哪家技术好 - mypinpai

在制造业向化、精密化转型的浪潮中,精密轧机作为金属加工领域的核心设备,直接决定了线材成型精度与生产效率。面对市场上良莠不齐的供应商,企业该如何选择?以下结合技术实力、定制能力与行业口碑,推荐2025年5家的…

Flask核心技能:从零上手视图函数

本文系统介绍了Flask框架中视图函数的定义与核心操作。详细讲解了如何使用装饰器绑定路由、通过request对象处理GET/POST请求数据、利用jsonify和render_template等返回多样化响应。文章还涵盖了自定义错误处理页面、常…

2025年质量好的单极性脉冲电源厂家信誉综合榜(权威) - 行业平台推荐

2025年质量好的单极性脉冲电源厂家信誉综合榜(权威)行业背景与市场趋势随着工业自动化、新能源、半导体制造等领域的快速发展,单极性脉冲电源作为关键电子设备组件,其市场需求呈现持续增长态势。2024-2025年,全球…

2025年张家港汽车贴膜门店年度排名:服务不错、信誉好的商铺 - 工业推荐榜

为帮助张家港及周边车主高效锁定适配自身需求的汽车贴膜服务商,避免选型走弯路,我们从技术落地能力(如贴膜工艺精度、设备专业性)、服务质量(含施工环境标准、售后保障体系)、真实客户口碑(侧重同行业项目反馈)…

2025年实力强的商用音乐平台排行榜,诚信的商用音乐品牌企业 - 工业品牌热点

为帮助企业与创作者高效锁定适配自身需求的商用音乐合作伙伴,避免版权侵权风险与选品走弯路,我们从版权合规性(如独立证书覆盖度、侵权风险保障)、曲库资源丰富度(含风格多样性、热门内容储备)、服务场景适配性(…

2025年五大靠谱装修公司推荐,口碑不错的装修品牌企业全解析 - mypinpai

在追求品质生活的当下,一个舒适美观的居住空间是多数家庭的理想追求。面对市场上鱼龙混杂的装修服务,如何挑选一家靠谱的装修公司成为许多业主的难题。以下依据不同装修需求类型,为你推荐2025年十大靠谱装修公司,助…

2025年热门的并网电源定制/双向电源定制品牌厂家排行榜 - 品牌宣传支持者

2025年热门的并网电源定制/双向电源定制品牌厂家排行榜行业背景与市场趋势随着全球能源结构转型加速推进,并网电源与双向电源市场迎来了前所未有的发展机遇。2024-2025年,在碳中和目标驱动下,分布式能源系统、智能微…

2025年口碑好的脉冲电源定制用户口碑最好的厂家榜 - 行业平台推荐

2025年口碑好的脉冲电源定制用户口碑的厂家榜开篇:行业背景与市场趋势随着工业4.0和智能制造时代的到来,脉冲电源作为关键电子设备在各行各业的应用日益广泛。从半导体制造、新能源开发到医疗设备、科研实验,高品质…

铸铝门庭院门专用塑粉厂家哪家好?2025塑粉生产厂家盘点 - 栗子测评

在门业制造领域,塑粉是决定铸铝门、庭院门外观质感与耐用性的关键材料。优质的专用塑粉能让门体兼具抗腐蚀、抗紫外线和美观的特性,而劣质塑粉则会导致门体短期内出现掉粉、褪色等问题。随着居民对入户门和庭院门品质…

实用指南:【JVM】Java为啥能跨平台?JDK/JRE/JVM的关系?

实用指南:【JVM】Java为啥能跨平台?JDK/JRE/JVM的关系?2025-12-10 08:33 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important…

2025外地靠谱的门店信息采集公司TOP5推荐:门店信息采集 - 工业推荐榜

数字化时代,线下终端数据是品牌决策的核心依据,但65%的品牌方仍面临门店陈列监控难、广告效果追踪贵、市场调研数据失真等痛点。据《2024线下零售数字化报告》显示,仅30%的企业拥有完善的线下数据采集体系,超40%的…

2025-12-10 GitHub 热点项目精选

🌟 2025-12-10 GitHub Python 热点项目精选(15个)每日同步 GitHub Trending 趋势,筛选优质 Python 项目,助力开发者快速把握技术风向标~📋 项目列表(按 Star 数排序) 1. microsoft/VibeVoiceVibeVoice 是微软…

2025年南京设计水平高的包装盒厂家推荐,塑料包装盒厂家精选 - 工业品牌热点

为帮助企业精准锁定适配自身需求的包装盒生产合作伙伴,避免选型走弯路,我们从设计定制能力(如细分场景适配、创意结构实现)、品质管控体系(含环保合规性、工艺精度)、交付响应效率(覆盖小批量急单、大批量稳定供…

2025年苏州有实力的玻璃贴膜公司推荐:口碑好的玻璃贴膜品牌 - myqiye

在汽车后市场领域,玻璃贴膜不仅是提升驾驶体验的刚需,更是保护车辆与保障安全的关键环节。面对市场上鱼龙混杂的服务商,如何找到有实力的玻璃贴膜公司?如何甄别高性价比的玻璃贴膜企业?又怎样锁定口碑好的玻璃贴膜…

2025年安阳短视频运营推广服务公司口碑推荐,看哪家实力强 - mypinpai

在短视频流量红利见顶、内容同质化严重的2025年,企业想靠短视频获客,选对运营推广服务商是关键。面对安阳本地鱼龙混杂的服务商,如何找到口碑好、效果实、服务稳的伙伴?以下结合安阳及周边(林州、鹤壁、滑县、濮阳…

2025年中国十大HAST老化试验箱生产厂家推荐:H看哪家产 - mypinpai

本榜单依托行业技术参数评测、客户交付案例调研与售后口碑反馈,筛选出十家具备核心技术壁垒的环境检测设备生产企业,为电子、汽车、军工等领域企业选型提供客观依据,助力匹配适配的可靠性试验解决方案伙伴。 TOP1 推…