OOP-实验5

news/2025/12/10 9:35:45/文章来源:https://www.cnblogs.com/dingxy-home/p/19329161

实验任务1

源代码 publisher.hpp,publisher.cpp,task1.cpp

点击查看代码 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; // 音乐艺术家名称
};
点击查看代码 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';
}
点击查看代码 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();
}

运行测试截图

img

  • 问题1:抽象类机制

  • (1)是什么决定了Publisher是抽象类?用一句话说明,并指出代码中的具体依据。

  • 回答:纯虚函数决定了Publisher是抽象类。可依据以下代码。

    virtual void publish() const = 0; // 纯虚函数,作为接口继承virtual void use() const = 0;     // 纯虚函数,作为接口继承
  • (2)如果在main.cpp里直接写Publisher p;能否编译通过?为什么?

  • 回答:不能编译通过。因为抽象类不能被实例化。

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

  • (1)BookFilmMusic必须实现哪两个函数才能通过编译?请写出其完整函数声明。

  • 回答:publishuse函数。完整声明如下。

    void publish() const override; // 接口void use() const override;     // 接口
  • (2)在publisher.cppFilm类实现中,把两个成员函数实现里的const去掉(保持函数体不变),重新编译,报错信息是什么?

  • 回答:无匹配的函数声明。

img

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

  • (1)在test1()里,for (Publisher *ptr : v)ptr的声明类型是什么?

  • 回答:Publisher*

  • (2)当循环执行到ptr->publish();时,ptr实际指向的对象类型分别有哪些?(按循环顺序写出)

  • 回答:BookFilmMusic

  • (3)基类Publisher的析构函数为何声明为virtual?若删除virtual,执行delete ptr;会出现什么问题?

  • 回答:确保通过基类指针删除派生类对象时,能够正确调用派生类的析构函数。若删除virtual,执行delete ptr;,会造成派生类资源未被正确释放。

实验任务2

源代码 book.hpp,book.cpp,booksale.hpp,booksale.cpp,task2.cpp

点击查看代码 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;           // 定价
};
点击查看代码 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;
}
点击查看代码 booksale.hpp
#pragma once#include <string>
#include "book.hpp"// 图书销售记录类BookSales:声明
class BookSale
{
public:BookSale(const Book &rb_, double sales_price_, int sales_amount_);int get_amount() const;     // 返回销售数量double get_revenue() const; // 返回营收friend std::ostream &operator<<(std::ostream &out, const BookSale &item);private:Book rb;double sales_price; // 售价int sales_amount;   // 销售数量
};
点击查看代码 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;
}
点击查看代码 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();
}

运行测试截图

img

  • 问题1:重载运算符<<

  • (1)找出运算符<<被重载了几处?分别用于什么类型?

  • 回答:2处,分别用于Book类、BookSale类。

  • (2)找出使用重载<<输出对象的代码,写在下面。

  • 回答:

Book类重载<<
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;
}
BookSale类重载<<
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;
}
  • 问题2:图书销售统计

  • (1)图书销售记录"按销售数量降序排序",代码是如何实现的?

  • 回答:调用algorithm库的sort函数,以自己实现的compare_by_amount作为排序规则,进行按销售数量降序排序。

// 按图书销售数量比较
bool compare_by_amount(const BookSale &x1, const BookSale &x2)
{return x1.get_amount() > x2.get_amount();
}
    // 按销售册数排序sort(sales_records.begin(), sales_records.end(), compare_by_amount);
  • (2)拓展(选答*):如果使用lambda表达式,如何实现"按销售数量降序排序"?

  • 回答:

    // 按销售册数排序sort(sales_records.begin(), sales_records.end(), [](const BookSale &x1, const BookSale &x2){ return x1.get_amount() > x2.get_amount(); });

实验任务3

源代码 task3_1.pp,task3_2.cpp

点击查看代码 task3_1.cpp
#include <iostream>// 类A的定义
class A
{
public:A(int x0, int y0);void display() const;private:int x, y;
};A::A(int x0, int y0) : x{x0}, y{y0}
{
}void A::display() const
{std::cout << x << ", " << y << '\n';
}// 类B的定义
class B
{
public:B(double x0, double y0);void display() const;private:double x, y;
};B::B(double x0, double y0) : x{x0}, y{y0}
{
}void B::display() const
{std::cout << x << ", " << y << '\n';
}void test()
{std::cout << "测试类A: " << '\n';A a(3, 4);a.display();std::cout << "\n测试类B: " << '\n';B b(3.2, 5.6);b.display();
}int main()
{test();
}
点击查看代码 task3_2.cpp
#include <iostream>
#include <string>// 定义类模板
template <typename T>
class X
{
public:X(T x0, T y0);void display();private:T x, y;
};template <typename T>
X<T>::X(T x0, T y0) : x{x0}, y{y0}
{
}template <typename T>
void X<T>::display()
{std::cout << x << ", " << y << '\n';
}void test()
{std::cout << "测试1: 用int实例化类模板X" << '\n';X<int> x1(3, 4);x1.display();std::cout << "\n测试2:用double实例化类模板X" << '\n';X<double> x2(3.2, 5.6);x2.display();std::cout << "\n测试3: 用string实例化类模板X" << '\n';X<std::string> x3("hello", "oop");x3.display();
}int main()
{test();
}

运行测试截图

task3_1.cpp

img

task3_2.cpp

img

实验任务4

源代码 Pet.hpp,task4.cpp

点击查看代码 Pet.hpp
#pragma once#include <string>class MachinePet
{
public:MachinePet(const std::string &_nickname) : nickname(_nickname) {}virtual ~MachinePet() = default;std::string get_nickname() const{return nickname;}virtual std::string talk() const = 0;protected:std::string nickname;
};class PetCat : public MachinePet
{
public:PetCat(const std::string &_nickname) : MachinePet(_nickname) {}std::string talk() const override{return "miao wu~";}
};class PetDog : public MachinePet
{
public:PetDog(const std::string &_nickname) : MachinePet(_nickname) {}std::string talk() const override{return "wang wang~";}
};
点击查看代码 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();
}

运行测试截图

img

实验任务5

源代码 Complex.hpp,task5.cpp

点击查看代码 Complex.hpp
#pragma oncetemplate <typename T>
class Complex
{
public:Complex(T r = T(), T i = T()) : real(r), imag(i) {}Complex(const Complex<T> &other) : real(other.real), imag(other.imag) {}T get_real() const{return real;}T get_imag() const{return imag;}Complex<T> operator+(const Complex<T> &other) const{return Complex<T>(real + other.real, imag + other.imag);}Complex<T> &operator+=(const Complex<T> &other){real += other.real;imag += other.imag;return *this;}bool operator==(const Complex<T> &other) const{return real == other.real && imag == other.imag;}friend std::ostream &operator<<(std::ostream &os, const Complex<T> &c){os << c.real << (c.imag >= 0 ? " + " : " - ") << std::abs(c.imag) << "i";return os;}friend std::istream &operator>>(std::istream &is, Complex<T> &c){is >> c.real >> c.imag;return is;}private:T real;T imag;
};
点击查看代码 task5.cpp
#include <iostream>
#include "Complex.hpp"void test1()
{using std::boolalpha;using std::cout;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();
}

运行测试截图

img

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

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

相关文章

想在藁城区农村盖房子,靠谱的自建房公司推荐。河北石家庄藁城区自建房公司/机构权威测评推荐排行榜。 - 苏木2025

想在藁城区农村盖房子,靠谱的自建房公司推荐。河北石家庄藁城区自建房公司/机构权威测评推荐排行榜。 一、引言 十年前,藁城区农村盖房还停留在“找本村工匠、画简易草图”的粗放模式。从滹沱河沿岸平原的砖瓦房,到…

【IEEE出版 | EI检索】第二届能源技术与电气电力国际学术会议 (ETEP 2025)、第五届电子信息工程与计算机通信国际学术会议(EIECC 2025)

由南华大学主办、哈尔滨工业大学和华北电力大学支持的第二届能源技术与电气电力国际学术会议(ETEP 2025)将于2025年12月26日至28日在中国衡阳举行。第五届电子信息工程与计算机通信国际学术会议(EIECC 2025)将于20…

1210随笔

今天准备复习软件设计。 先看一下以前写的代码: // 计算机产品类 class Computer { private String type; // 计算机类型(笔记本/台式机) private String cpu; // CPU private String memory; // …

2025年安阳地区短视频运营推广推荐,5家权威服务商深度解析 - 工业推荐榜

在短视频流量红利持续释放的当下,企业能否抓住抖音、快手、小红书等平台的获客机会,直接决定了线上业务的增长速度。面对市场上鱼龙混杂的服务商,如何找到既专业又靠谱的合作伙伴?以下结合安阳本地及周边市场,为你…

2025年中国砂光辊厂家推荐:看哪家技术实力强、产品质量优? - myqiye

本榜单依托全维度市场调研与真实行业口碑,深度筛选出五家砂光辊领域标杆企业,为下游制造业企业选型提供客观依据,助力精准匹配适配的服务伙伴。 TOP1 推荐:常熟卓世橡胶制品有限公司 推荐指数:★★★★★ 口碑评分…

2025年口碑不错的PPT模板公司排名,信誉好的PPT模板机 - mypinpai

在数字化办公时代,一份专业、美观的PPT是职场人高效传达信息的利器——无论是项目汇报、产品路演还是课程展示,优质PPT都能让内容事半功倍。但面对市场上参差不齐的PPT模板资源,如何找到口碑不错的PPT模板公司和信誉…

2025年全国抛丸机服务商排名,钢管抛丸机厂家/履带式抛丸机 - 工业品牌热点

抛丸清理设备是工业表面处理领域的核心支撑,直接影响工件质量与生产效率。为帮助企业精准匹配适配自身需求的设备供应商,避免因选型不当导致的生产损失,本文从产品技术成熟度、定制化方案能力、全周期服务质量、环保…

四川柴油发电机组厂家哪家质量好?求推荐 - 朴素的承诺

四川柴油发电机组厂家哪家质量好?求推荐在能源需求多元化的今天,柴油发电机组作为工业生产、能源保障、应急供电的核心装备,其质量稳定性与性能可靠性直接关系到企业生产安全与社会效益。面对四川市场上众多柴油发电…

威榜单!2025年四川中药材种苗基地公司实力排名 - 朴素的承诺

威榜单!2025年四川中药材种苗基地公司实力排名在秦巴山脉生态禀赋与川蜀道地药材积淀的双重加持下,四川中药材种苗产业已成为乡村振兴的核心动能。2025 年度四川中药材种苗基地实力测评今日揭晓,本次评选围绕推荐指…

2025年上海继承律师权威精选榜单:离婚房产律所/婚姻律所/房产律所服务商推荐 - 品牌推荐官

一套静安区的老洋房继承案里,律师需要查阅三代人的家庭档案,比对两份不同年代的遗嘱,还要协调三位身在海外、时区各异的继承人——这只是上海每年超过10万起继承案件中的寻常一幕。 在上海,随着社会财富积累和家庭…

成都二手发电机组厂家推荐:2025 年客户案例榜发布 - 朴素的承诺

成都二手发电机组厂家推荐:2025 年客户案例榜发布—— 四川康沃动力登顶 TOP1,央企背书实力领跑西南市场一、行业趋势洞察:二手发电机组迎来黄金发展期2025 年中国二手柴油发电机组市场规模已达 38 亿元,年均复合增…

成都 300KW 汽油发电机实力厂家推荐 ?求靠谱推荐 - 朴素的承诺

成都 300KW 汽油发电机实力厂家推荐 ?求靠谱推荐选择一家实力过硬的厂家,是保障供电无忧的关键。位于成都青白江区的四川康沃动力科技有限公司,作为国有参股的高端装备制造企业、口碑出众的成都发电机组厂家,凭借多…

深入解析:Go初级开发者的学习迷宫:AI导航下的捷径与陷阱——老码农的指南针

深入解析:Go初级开发者的学习迷宫:AI导航下的捷径与陷阱——老码农的指南针pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-fam…

2025年成都住人集装箱厂家推荐:靠谱服务商榜单 - 朴素的承诺

2025 年成都住人集装箱厂家推荐:靠谱服务商榜单随着城市化进程加速与环保建筑理念普及,成都住人集装箱市场迎来蓬勃发展。据四川省住建厅数据,2024 年成都活动房市场规模达 28.7 亿元,预计 2025 年将突破 33 亿元。…

2025 年热门的成都发电机行业内源头厂家排行榜 - 朴素的承诺

2025 年热门的成都发电机行业内源头厂家排行榜2025 年中国发电机市场规模预计达 4947.65 亿元,绿色化、智能化成为行业核心发展趋势。成都作为中西部能源装备制造核心枢纽,依托 “东数西算” 工程与新能源产业布局,…

102302145 黄加鸿 数据采集与融合技术作业4

作业4目录作业4作业①1)代码与结果2)心得体会3)Gitee链接作业②1)代码与结果2)心得体会3)Gitee链接作业③1)代码与结果2)心得体会作业① 1)代码与结果 目标:使用Selenium框架+ MySQL数据库存储技术路线爬取“…

沧县农村自建房找谁好?河北省沧州市沧县自建房公司 / 机构深度评测口碑推荐榜 - 苏木2025

沧县农村自建房找谁好?河北省沧州市沧县自建房公司 / 机构深度评测口碑推荐榜 一、引言:沧县农村自建房的 “专业化转型” 沧县地处河北省东南部,隶属于沧州市,县域内平原广袤,临近渤海湾,属温带季风气候,四季分…

盘点2025年:十大热门化妆品集合店加盟代理项目,排行前列的化妆品集合店加盟代理品牌怎么选择优质企业盘点及核心优势详细解读 - 品牌推荐师

随着消费升级与美妆市场的持续扩容,化妆品集合店以其丰富的品牌矩阵和高效的选品能力,成为连接品牌与消费者的重要渠道。对于创业者而言,选择一个具备强大供应链、成熟运营体系及稳定市场口碑的加盟代理品牌,是切入…