实验五
实验任务一:
#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 <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
#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
运行结果为:

问题一:
(1)决定 Publisher 是抽象类的原因是它包含至少一个纯虚函数。具体依据是代码中的两个纯虚函数声明:virtual void publish() const = 0; 和 virtual void use() const = 0;(使用 = 0 语法标记为纯虚函数)。
(2)不能编译通过。因为 Publisher 是抽象类,它包含纯虚函数,编译器不允许直接创建抽象类的实例对象。要使用 Publisher 必须通过指针或引用指向其具体派生类的对象。
问题二:
(1)这三个派生类必须实现 Publisher 中声明的两个纯虚函数,完整函数声明为:void publish() const override; 和 void use() const override;。这两个函数在基类中是纯虚函数,派生类必须提供具体实现才能成为具体类,否则派生类也会成为抽象类
(2)编译会报错,错误信息大致是:"函数签名不匹配,不是对基类虚函数的重写" 或 "不能覆盖基类的虚函数"。具体而言,编译器会指出 Film::publish() 和 Film::use() 没有正确覆盖基类的 Publisher::publish() const 和 Publisher::use() const,因为函数签名中的 const 限定符不一致,导致这是两个不同的函数,而不是有效的重写(override)。
问题三:
(1)ptr 的声明类型是 Publisher*,即指向 Publisher 基类的指针类型。这个声明类型是编译器在编译时看到的类型。
(2)按循环顺序,ptr 实际指向的对象类型分别是:第一次循环指向 Book 类型(《Harry Potter》),第二次循环指向 Film 类型(《The Godfather》),第三次循环指向 Music 类型(《Blowing in the wind》)。这些实际类型在运行时通过虚函数表动态确定。
(3)基类析构函数声明为 virtual 是为了确保通过基类指针删除派生类对象时,能够正确调用派生类的析构函数。如果删除 virtual,执行 delete ptr 时只会调用基类 Publisher 的析构函数,而不会调用 Book、Film、Music 等派生类的析构函数,导致派生类特有的资源(如 std::string 成员)无法正确释放,造成资源泄漏。这是一种典型的内存管理错误。
实验任务二:
#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 "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> #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 <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
#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
运行结果为:

问题一:
(1)两处,第一处用于BOOK类型,第二处用于booksale类型
(2)在 booksale.cpp 的 operator<< 重载中:out << item.rb << '\n'(输出 Book 对象);在 test.cpp 的 test() 函数中:cout << record << '\n'(输出 BookSale 对象);另外在 booksale.cpp 的 operator<< 重载实现中,通过调用 Book 的 << 重载来输出图书基本信息。
问题二:
(1)定义比较函数 compare_by_amount:返回 x1.get_amount() > x2.get_amount(),使用 std::sort 算法:sort(sales_records.begin(), sales_records.end(), compare_by_amount),比较函数返回 true 时,第一个参数排在第二个参数前面,由于是 > 比较,实现了降序排列
实验任务三:
无需写入实验博客文档
实验任务四:
#pragma once #include <string> // 机器宠物抽象类 MachinePet 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; // 昵称 }; // 电子宠物猫类 PetCat class PetCat : public MachinePet { public: PetCat(const std::string &nickname_ = "") : MachinePet(nickname_) {} std::string talk() const override { return "miao"; } }; // 电子宠物狗类 PetDog class PetDog : public MachinePet { public: PetDog(const std::string &nickname_ = "") : MachinePet(nickname_) {} std::string talk() const override { return "wang"; } };
#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
运行结果为:

实验任务五:
#pragma once #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; } // 运算符重载 Complex& operator+=(const Complex& other) { real += other.real; imag += other.imag; return *this; } Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } bool operator==(const Complex& other) const { return (real == other.real) && (imag == other.imag); } // 友元函数重载输入输出运算符 template<typename U> friend std::ostream& operator<<(std::ostream& out, const Complex<U>& c); template<typename U> friend std::istream& operator>>(std::istream& in, Complex<U>& c); }; // 输出运算符重载 template<typename T> std::ostream& operator<<(std::ostream& out, const Complex<T>& c) { out << "(" << c.real << ", " << c.imag << ")"; return out; } // 输入运算符重载 template<typename T> std::istream& operator>>(std::istream& in, Complex<T>& c) { in >> c.real >> c.imag; return in; }
#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
运行结果为:


浙公网安备 33010602011771号