当前位置: 首页 > news >正文

OOP实验五

实验任务一

源代码:

#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.cpp
#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.hpp
#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();
}
task1.cpp

其中由于我使用的编译器为devc++,task1.cpp中test2智能指针无法运行成功已注释掉。

运行结果:

屏幕截图 2025-12-10 085752

问题:

Q1:

  (1)决定publisher是抽象类的原因:它里面包含了“纯虚函数”,纯虚函数只有声明、没有定义,不能用来直接创建对象。

  具体依据:virtual void publish() const = 0;virtual void use() const=0;

  (2)不能编译通过。publisher是一个抽象类,它的存在是为了让别的类继承它就比如说book和film,所以单独使用它不能创建对象。

Q2:

  (1)它们必须实现从 Publisher 类继承下来的两个纯虚函数:publish和use。

   必须实现的具体函数声明:void publish() const override; void use() const override

  (2)如果去掉了const,那么函数void publish()和基类要求的void publish() coonst被认为是两个不同的函数。故而在film类中就没有成功重写纯虚函数,导致编译失败。

Q3:

  (1)ptr 的声明类型是 Publisher*,也就是“指向 Publisher 类对象的指针。

  (2)第一次循环:指向一个 Book 类对象。第二次循环:指向一个 Film 类对象。第三次循环:指向一个 Music 类对象。

  (3)这是为了确保当用基类Publisher的指针去删除一个派生类对象时,程序能够正确地调用到派生类自己的析构函数。

  若删除virtual会出现的问题:当执行 delete ptr时,编译器只会调用基类 Publisher 的析构函数,而不会调用指针实际指向的那个派生类的析构函数。这会导致派生类对象中独有的部分可能得不到清理。

 

 

实验任务二

源代码:

#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.cpp
#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.hpp
#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.cpp
#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.hpp
#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();
}
task2.cpp

运行结果:

屏幕截图 2025-12-10 090915

问题:

Q1:

  (1)在代码中,<< 运算符被重载了 2 次:第一次重载是为了输出Book类的对象。第二次重载是为了输出BookSale类的对象。

  (2)cout << record << '\n';  

Q2:

  (1)利用编写的compare_by_amount函数比较两本书的销量,如果第一本销量大于第二本,就返回true。然后调用sort函数,使其销量从高到低排序。

 

 

实验任务三:

源代码:

#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_1.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_2.cpp

运行结果:

task3_1.cpp

屏幕截图 2025-12-10 092447

task3_2.cpp

屏幕截图 2025-12-10 092648

 

 

实验任务四

源代码:

#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();
}
task4.cpp
#include <string>
class MachinePet {
protected:std::string nickname; public:MachinePet(const std::string& name) : nickname(name) {}std::string get_nickname() const {return nickname;}virtual std::string talk() const = 0;virtual ~MachinePet() {}
};
class PetCat : public MachinePet {
public:PetCat(const std::string& name) : MachinePet(name) {}std::string talk() const override {return "meow";}
};
class PetDog : public MachinePet {
public:PetDog(const std::string& name) : MachinePet(name) {}std::string talk() const override {return "wang";}
};
pet.hpp

运行结果:

屏幕截图 2025-12-11 104208

(智能指针无法运行已被注释)

 

 

实验任务五

源代码:

#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();
}
task5.cpp
#include <iostream>
#include <cmath>template<typename T>
class Complex {
private:T real;T imag;public:Complex(T r = 0, T i = 0);Complex(const Complex& other);T get_real() const;T get_imag() const;void set_real(T r);void set_imag(T i);Complex& operator+=(const Complex& other);Complex operator+(const Complex& other) const;bool operator==(const Complex& other) const;friend std::ostream& operator<<(std::ostream& out, const Complex& c) {out << c.real;if (c.imag >= 0) {out << " + " << c.imag << "i";} else {out << " - " << std::abs(c.imag) << "i";}return out;}friend std::istream& operator>>(std::istream& in, Complex& c) {in >> c.real >> c.imag;return in;}
};template<typename T>
Complex<T>::Complex(T r, T i) : real(r), imag(i) {}template<typename T>
Complex<T>::Complex(const Complex& other) : real(other.real), imag(other.imag) {}template<typename T>
T Complex<T>::get_real() const {return real;
}template<typename T>
T Complex<T>::get_imag() const {return imag;
}template<typename T>
void Complex<T>::set_real(T r) {real = r;
}template<typename T>
void Complex<T>::set_imag(T i) {imag = i;
}template<typename T>
Complex<T>& Complex<T>::operator+=(const Complex& other) {real += other.real;imag += other.imag;return *this;
}template<typename T>
Complex<T> Complex<T>::operator+(const Complex& other) const {return Complex<T>(real + other.real, imag + other.imag);
}template<typename T>
bool Complex<T>::operator==(const Complex& other) const {return (real == other.real) && (imag == other.imag);
}
Complex.hpp

运行结果:

屏幕截图 2025-12-13 113808

 

实验总结

 

在实验任务五中,按照学习通仿写类内声明类外定义发现很容易报错,需要多写很多声明模板参数,但如果在类内直接定义,可以避免链接出错、降低代码复杂性。故而经查阅总结面对模板类的友元函数,最好在类内定义和声明 ,它会自动与类模板的模板参数绑定。

http://www.jsqmd.com/news/98782/

相关文章:

  • 火山引擎AI大模型生态中,Anything-LLM的定位与发展前景
  • AI如何帮你自动生成cron定时任务代码
  • YOLOv11可能带来的技术革新预测
  • Dify平台支持多种数据库连接的配置方式汇总
  • 2025年国内正规的多媒体讲台电教桌供应厂家排名,多媒体讲台电教桌源头厂家哪家权威 - 品牌推荐师
  • Kubernetes入门不再难:AI助手教你5步搭建集群
  • 【酒馆实测】告别等待与红字!Grok-4-1-Fast才是RP玩家的终极快乐老家?
  • 宠物用品行业智能客服:痛点破解与发展路径
  • 2025年集装箱牛皮防滑纸厂家权威推荐榜:高强度、耐磨防滑,守护货物安全的工业包装实力之选 - 品牌企业推荐师(官方)
  • nn.Sequential vs 手动构建:效率对比实验
  • 用AI快速生成Flutter面试题答案与解析
  • 医疗时序预测漏长程依赖,后来补Transformer才稳住趋势
  • 小红书代运营服务商排行榜TOP10,短视频代运营团队/短视频代运营/抖音代运营/抖音推广/小红书代运营小红书代运营源头厂家排行榜单 - 品牌推荐师
  • PaddlePaddle深度学习平台镜像使用指南:支持清华源快速conda安装
  • 传统开发vsAI生成:扫雷游戏开发效率对比
  • linux安装kkFileView和libreOffice
  • 【建议收藏】AI大模型学习四层次:从工具使用到算法工程师的完整路径
  • AI 多模态数据处理系统:搞定“杂数据”,让数据真正帮企业做决策
  • 2025 年 12 月油品光谱仪厂家权威推荐榜:国产高精度替代进口,助力工业油液监测与设备预测性维护 - 品牌企业推荐师(官方)
  • 传统调试VS AI修复:SSL错误处理效率提升300%
  • 【PostgreSQL 17】14 并发与隔离
  • AutoGPT开源项目架构与核心功能解析
  • AI如何帮你自动生成Git补丁?快马平台实战
  • 企业级系统中verification failed:(0x1a)的5个真实案例解析
  • 2025年焦油柱状活性炭厂家权威推荐榜:深度解析高吸附性能与工业净化应用场景 - 品牌企业推荐师(官方)
  • 为什么 45 岁程序员精通各种技术体系,却连个面试机会都很难得到?
  • 数据库自然语言查询助手简易制作
  • AI如何帮你快速解决Selenium SessionNotCreatedException错误
  • 图解K8s部署可用性问题:从报错到解决的完整指南
  • kotaemon多平台API无缝对接指南