实验五

任务一

代码

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

效果

eaad3a3f6eeda79e4878b34f757a3720

 问题

问题1:抽象类机制
(1)Publisher类包含纯虚函数,因此是抽象类;代码依据是`publisher.hpp`中Publisher类声明了`virtual void publish() const = 0;`和`virtual void use() const = 0;`两个纯虚函数。
(2)不能编译通过;因为抽象类包含纯虚函数,无法实例化对象。


问题2:纯虚函数与接口继承
(1)必须实现的函数是:

void publish() const override;
void use() const override;

(2)报错信息为“'void Film::publish()' marked override, but does not override”“'void Film::use()' marked override, but does not override”,原因是派生类函数实现缺少`const`,与基类纯虚函数签名不匹配。


问题3:运行时多态与虚析构
(1)ptr的声明类型是`Publisher*`。
(2)实际指向的对象类型依次是Book、Film、Music。
(3)基类Publisher的析构函数声明为`virtual`,是为了通过基类指针删除派生类对象时,能正确调用派生类析构函数,避免内存泄漏;若删除`virtual`,执行`delete ptr;`时只会调用基类析构函数,派生类资源未被释放,会引发内存泄漏。

任务二

代码

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

效果

a3cb23cd5036e790a08084ad5eaf9e11

 问题

 问题1:重载运算符
(1)重载了2处;分别用于Book类型、BookSale类型。
(2)代码为:
for(auto &t: sales_lst) {
cout << t << endl;
cout << string(40, '-') << endl;
}


问题2:图书销售统计
(1)先定义`compare_by_amount`函数(实现销售数量降序的比较逻辑),再调用`sort(sales_lst.begin(), sales_lst.end(), compare_by_amount);`,使sales_lst按销售数量降序排列。
(2)用lambda表达式实现的sort语句:

sort(sales_lst.begin(), sales_lst.end(),
[](const BookSale &x1, const BookSale &x2) {
return x1.get_amount() > x2.get_amount();
}
);
任务三

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

效果

46faa5b30b05313a65f5bab09f0f4561

 

49a70fb05d98a4accc0733cdf6eeb0f7

 任务四

代码

 1 #pragma once
 2 #include <string>
 3 #include <string_view>  // 引入string_view优化字符串返回
 4 
 5 // 抽象基类:机器宠物(遵循接口隔离与单一职责原则)
 6 class MachinePet {
 7 public:
 8     // 构造函数:初始化昵称,避免默认构造带来的未初始化风险
 9     MachinePet(const std::string& nickname) : nickname_(nickname) {}
10     // 虚析构函数:确保派生类对象通过基类指针释放时资源不泄漏
11     virtual ~MachinePet() = default;
12 
13     // 内联获取昵称:简单接口直接内联,减少函数调用开销
14     inline std::string get_nickname() const {
15         return nickname_;
16     }
17 
18     // 纯虚函数:定义叫声接口,强制派生类实现(运行时多态核心)
19     virtual std::string_view talk() const = 0;
20 
21 private:
22     std::string nickname_;  // 私有成员封装,符合封装原则
23 };
24 
25 // 派生类:电子宠物猫(仅实现猫相关行为,遵循单一职责)
26 class PetCat : public MachinePet {
27 public:
28     // 构造函数:显式调用基类构造初始化昵称
29     PetCat(const std::string& nickname) : MachinePet(nickname) {}
30 
31     // 实现叫声接口:返回string_view避免临时string拷贝(优化性能)
32     std::string_view talk() const override {
33         return "miao wu~";  // 修正原代码符号错误,与实验预期一致
34     }
35 };
36 
37 // 派生类:电子宠物狗(仅实现狗相关行为,遵循单一职责)
38 class PetDog : public MachinePet {
39 public:
40     // 构造函数:显式调用基类构造初始化昵称
41     PetDog(const std::string& nickname) : MachinePet(nickname) {}
42 
43     // 实现叫声接口:返回string_view优化性能
44     std::string_view talk() const override {
45         return "wang wang~";
46     }
47 };
pet.hpp
 1 #include <iostream>
 2 #include <memory>
 3 #include <vector>
 4 #include "pet.hpp"
 5 
 6 // 测试1:原始指针管理
 7 void test1() {
 8     std::vector<MachinePet*> pets;
 9     pets.push_back(new PetCat("miku"));
10     pets.push_back(new PetDog("da huang"));
11 
12     // 范围for循环简化遍历,格式统一保持可读性
13     for (MachinePet* ptr : pets) {
14         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
15         delete ptr;  
16     }
17 }
18 
19 
20 void test2() {
21     std::vector<std::unique_ptr<MachinePet>> pets;
22     
23     pets.push_back(std::make_unique<PetCat>("miku"));
24     pets.push_back(std::make_unique<PetDog>("da huang"));
25 
26     
27     for (const auto& ptr : pets) {
28         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
29     }
30     
31 }
32 
33 
34 void test3() {
35     // MachinePet pet("little cutie");  
36     const PetCat cat("miku");
37     std::cout << cat.get_nickname() << " says " << cat.talk() << '\n';
38 
39     const PetDog dog("da huang");
40     std::cout << dog.get_nickname() << " says " << dog.talk() << '\n';
41 }
42 
43 int main() {
44     std::cout << "测试1: 使用原始指针\n";
45     test1();
46 
47     std::cout << "\n测试2: 使用智能指针\n";
48     test2();
49 
50     std::cout << "\n测试3: 直接使用类\n";
51     test3();
52 }
task4.cpp

效果

4a096d1b4132f9cbcec133706ef7dcb3

 任务五

代码

 1 #pragma once
 2 #include <iostream>
 3 #include <type_traits>
 4 
 5 template<typename T>
 6 class Complex {
 7     static_assert(std::is_arithmetic<T>::value, "Complex type must be arithmetic");
 8 private:
 9     T real_;
10     T imag_;
11 public:
12     Complex() : real_(0), imag_(0) {}
13     Complex(T real, T imag) : real_(real), imag_(imag) {}
14     Complex(const Complex<T>& other) : real_(other.real_), imag_(other.imag_) {}
15     T get_real() const { return real_; }
16     T get_imag() const { return imag_; }
17     Complex<T>& operator+=(const Complex<T>& rhs) {
18         real_ += rhs.real_;
19         imag_ += rhs.imag_;
20         return *this;
21     }
22     Complex<T> operator+(const Complex<T>& rhs) const {
23         return Complex<T>(real_ + rhs.real_, imag_ + rhs.imag_);
24     }
25     bool operator==(const Complex<T>& rhs) const {
26         return (real_ == rhs.real_) && (imag_ == rhs.imag_);
27     }
28     friend std::ostream& operator<<(std::ostream& os, const Complex<T>& c) {
29         os << c.real_;
30         c.imag_ >= 0 ? os << "+" << c.imag_ << "i" : os << "-" << -c.imag_ << "i";
31         return os;
32     }
33     friend std::istream& operator>>(std::istream& is, Complex<T>& c) {
34         is >> c.real_ >> c.imag_;
35         return is;
36     }
37 };
Complex.cpp
 1 #include <iostream>
 2 #include "Complex.hpp"
 3 
 4 void test1() {
 5     using std::cout;
 6     using std::boolalpha;
 7     Complex<int> c1(2, -5), c2(c1);
 8     cout << "c1 = " << c1 << '\n';
 9     cout << "c2 = " << c2 << '\n';
10     cout << "c1 + c2 = " << c1 + c2 << '\n';
11     c1 += c2;
12     cout << "c1 = " << c1 << '\n';
13     cout << boolalpha << (c1 == c2) << '\n';
14 }
15 
16 void test2() {
17     using std::cin;
18     using std::cout;
19     Complex<double> c1, c2;
20     cout << "Enter c1 and c2: ";
21     cin >> c1 >> c2;
22     cout << "c1 = " << c1 << '\n';
23     cout << "c2 = " << c2 << '\n';
24     const Complex<double> c3(c1);
25     cout << "c3.real = " << c3.get_real() << '\n';
26     cout << "c3.imag = " << c3.get_imag() << '\n';
27 }
28 
29 int main() {
30     std::cout << "自定义类模板Complex测试1: \n";
31     test1();
32     std::cout << "\n自定义类模板Complex测试2: \n";
33     test2();
34 }
task5.cpp

效果

66bd4b456eed3467a13b0bed2b6cf7f3

 

posted @ 2025-12-16 22:56  duser  阅读(1)  评论(0)    收藏  举报