实验作业5

实验任务1

代码

publisher.cpp

#include <iostream>
#include <string>
#include "publisher.hpp"// Publisher类:实现
Publisher::Publisher(const std::string &name_): name {name_} {
}// Book类: 实现
Book::Book(const std::string &name_ , const std::string &author_ ): Publisher{name_}, author{author_} {
}void Book::publish() const {std::cout << "Publishing book《" << name << "》 by " << author << '\n';
}void Book::use() const {std::cout << "Reading book 《" << name << "》 by " << author << '\n';
}// Film类:实现
Film::Film(const std::string &name_, const std::string &director_):Publisher{name_},director{director_} {
}void Film::publish() const {std::cout << "Publishing film <" << name << "> directed by " << director << '\n';
}void Film::use() const {std::cout << "Watching film <" << name << "> directed by " << director << '\n';
}// Music类:实现
Music::Music(const std::string &name_, const std::string &artist_): Publisher{name_}, artist{artist_} {
}void Music::publish() const {std::cout << "Publishing music <" << name << "> by " << artist << '\n';
}void Music::use() const {std::cout << "Listening to music <" << name << "> by " << artist << '\n';
}

 

publisher.hpp

#pragma once#include <string>// 发行/出版物类:Publisher (抽象类)
class Publisher {
public:Publisher(const std::string &name_ = "");            // 构造函数virtual ~Publisher() = default;public:virtual void publish() const = 0;                 // 纯虚函数,作为接口继承virtual void use() const = 0;                     // 纯虚函数,作为接口继承protected:std::string name;    // 发行/出版物名称
};// 图书类: Book
class Book: public Publisher {
public:Book(const std::string &name_ = "", const std::string &author_ = "");  // 构造函数public:void publish() const override;        // 接口void use() const override;            // 接口private:std::string author;          // 作者
};// 电影类: Film
class Film: public Publisher {
public:Film(const std::string &name_ = "", const std::string &director_ = "");   // 构造函数public:void publish() const override;    // 接口void use() const override;        // 接口            private:std::string director;        // 导演
};// 音乐类:Music
class Music: public Publisher {
public:Music(const std::string &name_ = "", const std::string &artist_ = "");public:void publish() const override;        // 接口void use() const override;            // 接口private:std::string artist;      // 音乐艺术家名称
};

 

task1.cpp

#include <memory>
#include <iostream>
#include <vector>
#include "publisher.hpp"void test1() {std::vector<Publisher *> v;v.push_back(new Book("Harry Potter", "J.K. Rowling"));v.push_back(new Film("The Godfather", "Francis Ford Coppola"));v.push_back(new Music("Blowing in the wind", "Bob Dylan"));for(Publisher *ptr: v) {ptr->publish();ptr->use();std::cout << '\n';delete ptr;}
}void test2() {std::vector<std::unique_ptr<Publisher>> v;v.push_back(std::make_unique<Book>("Harry Potter", "J.K. Rowling"));v.push_back(std::make_unique<Film>("The Godfather", "Francis Ford Coppola"));v.push_back(std::make_unique<Music>("Blowing in the wind", "Bob Dylan"));for(const auto &ptr: v) {ptr->publish();ptr->use();std::cout << '\n';}
}void test3() {Book book("A Philosophy of Software Design", "John Ousterhout");book.publish();book.use();
}int main() {std::cout << "运行时多态:纯虚函数、抽象类\n";std::cout << "\n测试1: 使用原始指针\n";test1();std::cout << "\n测试2: 使用智能指针\n";test2();std::cout << "\n测试3: 直接使用类\n";test3();
}

 

运行截图

image

 

问题回答

问题1:抽象类机制 

(1) Publisher 是抽象类,因为它包含纯虚函数。依据:publisher.hpp 中的 

virtual void publish() const = 0; 

virtual void use() const = 0;

(2) 在 main.cpp 中写 Publisher p; 不能编译通过,因为抽象类不能实例化。

问题2:纯虚函数与接口继承 

(1) Book、Film、Music 必须实现这两个函数: 

void publish() const override; 

void use() const override;

(2) 若在 Film 的实现中去掉 const,则会出现“没有与基类虚函数匹配的成员函数”之类的报错

error: ‘void Film::publish()’ marked ‘override’, but does not override 

error: ‘void Film::use()’ marked ‘override’, but does not override

问题3:运行时多态与虚析构

(1) test1() 中 ptr 的声明类型是 Publisher*。

(2) ptr->publish() 时实际对象类型依次是:Book、Film、Music。

(3) Publisher 的析构函数需要是 virtual,以便 delete ptr 时正确调用派生类析构函数;若删除 virtual,则会导致派生类析构函数不被调用,出现资源未释放或行为未定义的问题。

实验任务2

代码

task2.cpp

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "booksale.hpp"// 按图书销售数量比较
bool compare_by_amount(const BookSale &x1, const BookSale &x2) {return x1.get_amount() > x2.get_amount();
}void test() {using std::cin;using std::cout;using std::getline;using std::sort;using std::string;using std::vector;using std::ws;vector<BookSale> sales_records;         // 图书销售记录表int books_number;cout << "录入图书数量: ";cin >> books_number;cout << "录入图书销售记录\n";for(int i = 0; i < books_number; ++i) {string name, author, translator, isbn;double price;cout << string(20, '-') << "" << i+1 << "本图书信息录入" << string(20, '-') << '\n';cout << "录入书名: "; getline(cin>>ws, name);cout << "录入作者: "; getline(cin>>ws, author);cout << "录入译者: "; getline(cin>>ws, translator);cout << "录入isbn: "; getline(cin>>ws, isbn);cout << "录入定价: "; cin >> price;Book book(name, author, translator, isbn, price);double sales_price;int sales_amount;cout << "录入售价: "; cin >> sales_price;cout << "录入销售数量: "; cin >> sales_amount;BookSale record(book, sales_price, sales_amount);sales_records.push_back(record);}// 按销售册数排序
    sort(sales_records.begin(), sales_records.end(), compare_by_amount);// 按销售册数降序输出图书销售信息cout << string(20, '=') <<  "图书销售统计" << string(20, '=') << '\n';for(auto &record: sales_records) {cout << record << '\n';cout << string(40, '-') << '\n';}
}int main() {test();
}

 

book.cpp

#include <iomanip>
#include <iostream>
#include <string>
#include "book.hpp"// 图书描述信息类Book: 实现
Book::Book(const std::string &name_, const std::string &author_, const std::string &translator_, const std::string &isbn_, double price_):name{name_}, author{author_}, translator{translator_}, isbn{isbn_}, price{price_} {
}// 运算符<<重载实现
std::ostream& operator<<(std::ostream &out, const Book &book) {using std::left;using std::setw;out << left;out << setw(15) << "书名:" << book.name << '\n'<< setw(15) << "作者:" << book.author << '\n'<< setw(15) << "译者:" << book.translator << '\n'<< setw(15) << "ISBN:" << book.isbn << '\n'<< setw(15) << "定价:" << book.price;return out;
}

 

book.hpp

#pragma once
#include <string>// 图书描述信息类Book: 声明
class Book {
public:Book(const std::string &name_, const std::string &author_, const std::string &translator_, const std::string &isbn_, double price_);friend std::ostream& operator<<(std::ostream &out, const Book &book);private:std::string name;        // 书名std::string author;      // 作者std::string translator;  // 译者std::string isbn;        // isbn号double price;        // 定价
};

 

booksale.cpp

#include <iomanip>
#include <iostream>
#include <string>
#include "booksale.hpp"// 图书销售记录类BookSales:实现
BookSale::BookSale(const Book &rb_, double sales_price_, int sales_amount_): rb{rb_}, sales_price{sales_price_}, sales_amount{sales_amount_} {
}int BookSale::get_amount() const {return sales_amount;
}double BookSale::get_revenue() const {return sales_amount * sales_price;
}// 运算符<<重载实现
std::ostream& operator<<(std::ostream &out, const BookSale &item) {using std::left;using std::setw;out << left;out << item.rb << '\n'<< setw(15) << "售价:" << item.sales_price << '\n'<< setw(15) << "销售数量:" << item.sales_amount << '\n'<< setw(15) << "营收:" << item.get_revenue();return out;
}

 

booksale.hpp

#pragma once
#include <string>// 图书描述信息类Book: 声明
class Book {
public:Book(const std::string &name_, const std::string &author_, const std::string &translator_, const std::string &isbn_, double price_);friend std::ostream& operator<<(std::ostream &out, const Book &book);private:std::string name;        // 书名std::string author;      // 作者std::string translator;  // 译者std::string isbn;        // isbn号double price;        // 定价
};

 

运行截图

image

 

问题回答

问题1

(1) 共重载了2处,分别用于类型Book和类型BookSale。

(2) 使用重载<<输出对象的代码:

cout << t << endl;

out << item.rb << '\n'

问题2

(1) 先定义比较函数compare_by_amount,再调用sort并把该比较函数作为第三个参数,从而实现按销售数量降序排序。

(2) 使用lambda可写为 sort(sales_lst.begin(), sales_lst.end(), [](const BookSale &a, const BookSale &b){ return a.get_amount() > b.get_amount(); });

实验任务4

代码

pet.hpp

#ifndef PET_HPP
#define PET_HPP#include <string>class MachinePet {
protected:std::string nickname;public:explicit MachinePet(const std::string &name) : nickname(name) {}virtual ~MachinePet() = default;std::string get_nickname() const {return nickname;}virtual std::string talk() const = 0;
};class PetCat : public MachinePet {
public:explicit PetCat(const std::string &name) : MachinePet(name) {}std::string talk() const override {return "miao wu~";}
};class PetDog : public MachinePet {
public:explicit PetDog(const std::string &name) : MachinePet(name) {}std::string talk() const override {return "wang wang~";}
};#endif

 

task4.cpp

#include <iostream>
#include <memory>
#include <vector>
#include "pet.hpp"void test1() {std::vector<MachinePet *> pets;pets.push_back(new PetCat("miku"));pets.push_back(new PetDog("da huang"));for(MachinePet *ptr: pets) {std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';delete ptr;  // 须手动释放资源
    }   
}void test2() {std::vector<std::unique_ptr<MachinePet>> pets;pets.push_back(std::make_unique<PetCat>("miku"));pets.push_back(std::make_unique<PetDog>("da huang"));for(auto const &ptr: pets)std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
}void test3() {// MachinePet pet("little cutie");   // 编译报错:无法定义抽象类对象const PetCat cat("miku");std::cout << cat.get_nickname() << " says " << cat.talk() << '\n';const PetDog dog("da huang");std::cout << dog.get_nickname() << " says " << dog.talk() << '\n';
}int main() {std::cout << "测试1: 使用原始指针\n";test1();std::cout << "\n测试2: 使用智能指针\n";test2();std::cout << "\n测试3: 直接使用类\n";test3();
}

 

运行截图

 

image

 

 

实验任务5

代码

Complex.hpp

#ifndef COMPLEX_HPP
#define COMPLEX_HPP#include <iostream>template<typename T>
class Complex {
private:T real;T imag;public:Complex() : real(0), imag(0) {}Complex(T r, T i = 0) : real(r), imag(i) {}Complex(const Complex& other) : real(other.real), imag(other.imag) {}T get_real() const { return real; }T get_imag() const { return imag; }// c1 + c2Complex operator+(const Complex& rhs) const {return Complex(real + rhs.real, imag + rhs.imag);}// c1 += c2Complex& operator+=(const Complex& rhs) {real += rhs.real;imag += rhs.imag;return *this;}// c1 == c2bool operator==(const Complex& rhs) const {return (real == rhs.real) && (imag == rhs.imag);}template<typename U>friend std::ostream& operator<<(std::ostream& os, const Complex<U>& c);template<typename U>friend std::istream& operator>>(std::istream& is, Complex<U>& c);
};template<typename T>
std::ostream& operator<<(std::ostream& os, const Complex<T>& c) {os << c.real;if (c.imag < 0) os << " - ";else os << " + ";os << abs(c.imag) << 'i';return os;
}template<typename T>
std::istream& operator>>(std::istream& is, Complex<T>& c) {is >> c.real >> c.imag;return is;
}#endif

 

task5.cpp

#include <iostream>
#include "Complex.hpp"void test1() {using std::cout;using std::boolalpha;Complex<int> c1(2, -5), c2(c1);cout << "c1 = " << c1 << '\n';cout << "c2 = " << c2 << '\n';cout << "c1 + c2 = " << c1 + c2 << '\n';c1 += c2;cout << "c1 = " << c1 << '\n';cout << boolalpha << (c1 == c2) << '\n';
}void test2() {using std::cin;using std::cout;Complex<double> c1, c2;cout << "Enter c1 and c2: ";cin >> c1 >> c2;cout << "c1 = " << c1 << '\n';cout << "c2 = " << c2 << '\n';const Complex<double> c3(c1);cout << "c3.real = " << c3.get_real() << '\n';cout << "c3.imag = " << c3.get_imag() << '\n';
}int main() {std::cout << "自定义类模板Complex测试1: \n";test1();std::cout << "\n自定义类模板Complex测试2: \n";test2();
}

 

运行截图

image

 

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

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

相关文章

Docker容器化实践:从开发到生产的完整流程

前言 "在我电脑上能跑啊&#xff01;"这句话曾经是我们团队的口头禅。环境不一致导致的问题层出不穷&#xff0c;直到我们引入了Docker。 这篇文章分享我们的Docker实践经验。 一、为什么选择Docker&#xff1f; 1.1 传统部署的痛点 bash # 开发环境 Python 3.8 …

Python+Vue的校园自助洗衣服务管理系统 Pycharm django flask

收藏关注不迷路&#xff01;&#xff01;需要的小伙伴可以发链接或者截图给我 项目介绍 本系统共有管理员,用户2个角色&#xff0c;具体功能如下&#xff1a; 1.管理员角色的功能主要包括管理员登录&#xff0c;用户管理&#xff0c;洗衣机分类管理&#xff0c;洗衣机管理&…

Vosk开源语音识别:50MB离线神器,树莓派到手机全搞定

文章概要 Vosk是一款由阿尔汉格尔斯克国立技术大学团队开发的开源、离线优先语音识别工具包。其核心优势在于模型轻量、支持多语言且完全本地运行&#xff0c;无需网络连接。本文将解析Vosk如何在嵌入式设备和隐私敏感场景下&#xff0c;以极低的资源占用成为云端服务的替代方案…

大头针AI爆火背后:音乐创作平民化与华语乐坛的算法革命

近期&#xff0c;由酷狗音乐阿波罗声音实验室打造的AI虚拟歌手“大头针”凭借翻唱经典歌曲在抖音等平台爆火&#xff0c;单月涨粉超38万。其现象级传播不仅展示了生成式AI在音乐领域的强大能力&#xff0c;更引发了关于创作门槛崩塌、版权归属模糊及人类歌手价值存疑的深层争议…

模型推理 单多轮推理,gpu推理,lora推理和vllm(附代码示例)

模型推理 单多轮推理&#xff0c;gpu推理&#xff0c;lora推理和vllm 一、大语言模型推理基础 1. 推理与训练的核心差异 维度 模型训练 模型推理 硬件需求 需强大GPU集群、海量存储 硬件需求较低&#xff0c;支持CPU/GPU 计算逻辑 反向传播梯度下降&#xff0c;计算量大 仅前…

为什么Anthropic说:AI的未来是Skills不是Agent?

随着AI智能体&#xff08;Agent&#xff09;技术的快速演进&#xff0c;当前开发领域普遍存在一种认知偏差&#xff1a;针对不同细分场景和具体用例&#xff0c;开发者倾向于从零开始创建独立的Agent。 Anthropic公司的Barry Zhang与Mahesh Murag在近期演讲中颠覆了这一传统思…

A7.4.8 Response signaling

1. 原子操作完成的可见性定义 规则: 写响应(B通道)表明原子操作的结果已对所有必需观察者可见。 对于包含读响应的原子操作(AtomicLoad/Swap/Compare),从接收到第一个读数据项时起,操作结果就可见。 管理器可使用读响应或写响应中的任意一个作为操作完成的指示。 举例…

AXI-A7.4.9 Atomic transaction dependencies

这些规则定义了在执行AtomicLoad、AtomicSwap和AtomicCompare事务时,管理器(Master)和从设备(Subordinate)之间握手信号(VALID和READY)的时序约束。其核心目标是在保证原子操作正确性的前提下,最大限度地维持AXI协议的流水线化和通道独立性优势。 信号依赖关系核心原则…

AXI-A7.4.10 Support for Atomic transactions(1)

Atomic_Transactions 属性是一个简单的布尔标志,用于明确声明一个AXI接口组件(可以是管理器、从设备或互连组件)是否支持原子事务扩展功能。其核心规定如下: 属性值: True:该组件完全支持原子事务。 False:该组件不支持原子事务(此为默认值)。 关键要求:如果一个组…

AXI-A7.4.10 Support for Atomic transactions(2)

Manager support 该部分描述了AXI协议中,管理器(Manager,如CPU、DMA等主设备)对原子事务的一种向后兼容性支持机制。其核心在于,即使一个管理器本身具备发起原子事务的能力,它也可以被配置为不发起这类事务,以确保在不支持原子操作的旧系统中能正常工作。这是通过一个可…

关于xml动态sql的思路

要灵活使用动态sql&#xff0c; 除了掌握sql的语法&#xff0c;还要掌握&#xff0c;如何灵活使用动态sql的时机。 我们来看看这个xml&#xff0c;提供了哪几类机制 条件控制&#xff1a;, // 结构优化&#xff1a;, , 集合遍历&#xff1a; 变量绑定&#xff1a; ok&#xff…

【JS】JS进阶--编程思想、面向对象构造函数、原型、深浅拷贝、异常处理、this处理、防抖节流

文章目录一、编程思想1. 面向过程编程2. 面向对象编程3. 面向过程 vs 面向对象二、构造函数与原型4. 构造函数实现面向对象5. 构造函数的内存问题三、原型系统6. 原型对象概念7. 原型中的 this 指向8. 扩展内置对象原型9. constructor 属性10. 对象原型 __proto__11. 原型继承1…

一文学会设计模式之行为型模式及最佳实现

设计模式概述 1. 创建型模式 (Creational Patterns) 关注点&#xff1a;对象的创建过程 核心思想&#xff1a;将对象的创建与使用分离&#xff0c;避免紧耦合 解决的问题&#xff1a;如何创建对象&#xff0c;使系统更灵活、可扩展 特点&#xff1a;隔离对象的创建和使用&#…

脚本网页 地球演化

<!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0, maximum-scale1.0, user-scalableno"><title>地球生命演…

介观交通流仿真软件:Aimsun Next_(9).仿真结果分析与可视化

仿真结果分析与可视化 在交通流仿真过程中&#xff0c;仿真结果的分析与可视化是至关重要的步骤。通过对仿真结果的分析&#xff0c;我们可以验证模型的有效性&#xff0c;评估交通策略的效果&#xff0c;并提取有用的信息以支持决策。可视化则帮助我们将这些复杂的数据以直观的…

TensorFlow 深度解析:从基础到实战的全维度指南

引言&#xff1a;人工智能时代的核心驱动力 在人工智能与机器学习飞速发展的今天&#xff0c;深度学习框架已成为技术落地的核心基础设施。TensorFlow 作为谷歌开源的深度学习框架&#xff0c;自 2015 年首次发布以来&#xff0c;凭借其强大的功能、灵活的架构和庞大的社区支持…

介观交通流仿真软件:Aimsun Next_(10).动态交通分配

动态交通分配 1. 动态交通分配概述 动态交通分配&#xff08;Dynamic Traffic Assignment, DTA&#xff09;是交通仿真中的一项关键技术&#xff0c;它不仅考虑交通网络的静态属性&#xff0c;还模拟交通流量随时间和空间的变化。与静态交通分配不同&#xff0c;动态交通分配能…

介观交通流仿真软件:Aimsun Next_(11).事件和策略建模

事件和策略建模 在Aimsun Next中&#xff0c;事件和策略建模是介观交通流仿真中非常重要的部分。通过事件和策略建模&#xff0c;用户可以模拟各种交通事件和管理策略&#xff0c;从而更准确地预测交通系统的行为和性能。本节将详细介绍如何在Aimsun Next中进行事件和策略建模&…

介观交通流仿真软件:Aimsun Next_(12).交通仿真运行与管理

交通仿真运行与管理 1. 仿真运行的基本概念 在交通仿真软件中&#xff0c;仿真运行是指通过模拟实际交通系统的运行过程来生成交通流数据和评估交通性能。Aimsun Next 提供了强大的仿真引擎&#xff0c;可以处理从微观到宏观的各种交通仿真需求。介观交通流仿真介于微观和宏观之…

介观交通流仿真软件:Aimsun Next_(15).AimsunNext的插件开发

AimsunNext的插件开发 1. 插件开发概述 在Aimsun Next中&#xff0c;插件开发是扩展其功能的重要手段。通过插件开发&#xff0c;用户可以自定义交通仿真模型、算法、用户界面等&#xff0c;以满足特定的项目需求。Aimsun Next提供了丰富的API和开发工具&#xff0c;支持Python…