实验5

##实验任务1

#代码

publisher.hpp

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 // 发行/出版物类:Publisher (抽象类)
 6 class Publisher {
 7 public:
 8     Publisher(const std::string &name_ = "");            // 构造函数
 9     virtual ~Publisher() = default;
10 
11 public:
12     virtual void publish() const = 0;                 // 纯虚函数,作为接口继承
13     virtual void use() const = 0;                     // 纯虚函数,作为接口继承
14 
15 protected:
16     std::string name;    // 发行/出版物名称
17 };
18 
19 // 图书类: Book
20 class Book: public Publisher {
21 public:
22     Book(const std::string &name_ = "", const std::string &author_ = "");  // 构造函数
23 
24 public:
25     void publish() const override;        // 接口
26     void use() const override;            // 接口
27 
28 private:
29     std::string author;          // 作者
30 };
31 
32 // 电影类: Film
33 class Film: public Publisher {
34 public:
35     Film(const std::string &name_ = "", const std::string &director_ = "");   // 构造函数
36 
37 public:
38     void publish() const override;    // 接口
39     void use() const override;        // 接口            
40 
41 private:
42     std::string director;        // 导演
43 };
44 
45 
46 // 音乐类:Music
47 class Music: public Publisher {
48 public:
49     Music(const std::string &name_ = "", const std::string &artist_ = "");
50 
51 public:
52     void publish() const override;        // 接口
53     void use() const override;            // 接口
54 
55 private:
56     std::string artist;      // 音乐艺术家名称
57 };

publisher.cpp

 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 
10 // Book类: 实现
11 Book::Book(const std::string &name_ , const std::string &author_ ): Publisher{name_}, author{author_} {
12 }
13 
14 void Book::publish() const {
15     std::cout << "Publishing book《" << name << "》 by " << author << '\n';
16 }
17 
18 void Book::use() const {
19     std::cout << "Reading book 《" << name << "》 by " << author << '\n';
20 }
21 
22 
23 // Film类:实现
24 Film::Film(const std::string &name_, const std::string &director_):Publisher{name_},director{director_} {
25 }
26 
27 void Film::publish() const {
28     std::cout << "Publishing film <" << name << "> directed by " << director << '\n';
29 }
30 
31 void Film::use() const {
32     std::cout << "Watching film <" << name << "> directed by " << director << '\n';
33 }
34 
35 
36 // Music类:实现
37 Music::Music(const std::string &name_, const std::string &artist_): Publisher{name_}, artist{artist_} {
38 }
39 
40 void Music::publish() const {
41     std::cout << "Publishing music <" << name << "> by " << artist << '\n';
42 }
43 
44 void Music::use() const {
45     std::cout << "Listening to music <" << name << "> by " << artist << '\n';
46 }

task1.cpp

 1 #include <memory>
 2 #include <iostream>
 3 #include <vector>
 4 #include "publisher.hpp"
 5 
 6 void test1() {
 7    std::vector<Publisher *> v;
 8 
 9    v.push_back(new Book("Harry Potter", "J.K. Rowling"));
10    v.push_back(new Film("The Godfather", "Francis Ford Coppola"));
11    v.push_back(new Music("Blowing in the wind", "Bob Dylan"));
12 
13    for(Publisher *ptr: v) {
14         ptr->publish();
15         ptr->use();
16         std::cout << '\n';
17         delete ptr;
18    }
19 }
20 
21 void test2() {
22     std::vector<std::unique_ptr<Publisher>> v;
23 
24     v.push_back(std::make_unique<Book>("Harry Potter", "J.K. Rowling"));
25     v.push_back(std::make_unique<Film>("The Godfather", "Francis Ford Coppola"));
26     v.push_back(std::make_unique<Music>("Blowing in the wind", "Bob Dylan"));
27 
28     for(const auto &ptr: v) {
29         ptr->publish();
30         ptr->use();
31         std::cout << '\n';
32     }
33 }
34 
35 void test3() {
36     Book book("A Philosophy of Software Design", "John Ousterhout");
37     book.publish();
38     book.use();
39 }
40 
41 int main() {
42     std::cout << "运行时多态:纯虚函数、抽象类\n";
43 
44     std::cout << "\n测试1: 使用原始指针\n";
45     test1();
46 
47     std::cout << "\n测试2: 使用智能指针\n";
48     test2();
49 
50     std::cout << "\n测试3: 直接使用类\n";
51     test3();
52 }

#运行结果

image

 (由于我的Dev-c++版本低,std::make_unique<>不能够编译,因此编译运行时将test2()部分给注释起来了)

#问题

1.(1)包含了纯虚函数,

 virtual void publish() const = 0;

virtual void use() const = 0;
(2)不能编译通过,因为 Publisher 是抽象类,不能直接实例化对象

2.(1)必须实现基类中的两个纯虚函数才能通过编译
void publish() const override; 
void use() const override;

 (2)

image

 报错的核心是函数签名不匹配,编译器会提示子类的函数没有正确覆写基类的纯虚函数

3.(1)基类指针类型Publisher*

(2)Book Film Music

(3)为了实现多态析构函数,调用基类析构函数前,先调用子类的析构函数,保证对象资源被完整释放;

若删除virtual,将不会调用子类的析构函数,导致子类的资源泄漏。

##实验任务2

#代码

book.hpp

 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 
13     friend std::ostream& operator<<(std::ostream &out, const Book &book);
14 
15 private:
16     std::string name;        // 书名
17     std::string author;      // 作者
18     std::string translator;  // 译者
19     std::string isbn;        // isbn号
20     double price;        // 定价
21 };

book.cpp

 1 #include <iomanip>
 2 #include <iostream>
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 
 7 // 图书描述信息类Book: 实现
 8 Book::Book(const std::string &name_, 
 9           const std::string &author_, 
10           const std::string &translator_, 
11           const std::string &isbn_, 
12           double price_):name{name_}, author{author_}, translator{translator_}, 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 }

booksale.hpp

 1 #pragma once
 2 
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 // 图书销售记录类BookSales:声明
 7 class BookSale {
 8 public:
 9     BookSale(const Book &rb_, double sales_price_, int sales_amount_);
10     int get_amount() const;   // 返回销售数量
11     double get_revenue() const;   // 返回营收
12     
13     friend std::ostream& operator<<(std::ostream &out, const BookSale &item);
14 
15 private:
16     Book rb;         
17     double sales_price;      // 售价
18     int sales_amount;       // 销售数量
19 };

booksale.cpp

 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_}, sales_amount{sales_amount_} {
10 }
11 
12 int BookSale::get_amount() const {
13     return sales_amount;
14 }
15 
16 double BookSale::get_revenue() const {
17     return sales_amount * sales_price;
18 }
19 
20 // 运算符<<重载实现
21 std::ostream& operator<<(std::ostream &out, const BookSale &item) {
22     using std::left;
23     using std::setw;
24     
25     out << left;
26     out << item.rb << '\n'
27         << setw(15) << "售价:" << item.sales_price << '\n'
28         << setw(15) << "销售数量:" << item.sales_amount << '\n'
29         << setw(15) << "营收:" << item.get_revenue();
30 
31     return out;
32 }

task2.cpp

 1 #include <algorithm>
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include "booksale.hpp"
 7 
 8 // 按图书销售数量比较
 9 bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
10     return x1.get_amount() > x2.get_amount();
11 }
12 
13 void test() {
14     using std::cin;
15     using std::cout;
16     using std::getline;
17     using std::sort;
18     using std::string;
19     using std::vector;
20     using std::ws;
21 
22     vector<BookSale> sales_records;         // 图书销售记录表
23 
24     int books_number;
25     cout << "录入图书数量: ";
26     cin >> books_number;
27 
28     cout << "录入图书销售记录\n";
29     for(int i = 0; i < books_number; ++i) {
30         string name, author, translator, isbn;
31         double price;
32         cout << string(20, '-') << "" << i+1 << "本图书信息录入" << string(20, '-') << '\n';
33         cout << "录入书名: "; getline(cin>>ws, name);
34         cout << "录入作者: "; getline(cin>>ws, author);
35         cout << "录入译者: "; getline(cin>>ws, translator);
36         cout << "录入isbn: "; getline(cin>>ws, isbn);
37         cout << "录入定价: "; cin >> price;
38 
39         Book book(name, author, translator, isbn, price);
40 
41         double sales_price;
42         int sales_amount;
43 
44         cout << "录入售价: "; cin >> sales_price;
45         cout << "录入销售数量: "; cin >> sales_amount;
46 
47         BookSale record(book, sales_price, sales_amount);
48         sales_records.push_back(record);
49     }
50 
51     // 按销售册数排序
52     sort(sales_records.begin(), sales_records.end(), compare_by_amount);
53 
54     // 按销售册数降序输出图书销售信息
55     cout << string(20, '=') <<  "图书销售统计" << string(20, '=') << '\n';
56     for(auto &record: sales_records) {
57         cout << record << '\n';
58         cout << string(40, '-') << '\n';
59     }
60 }
61 
62 int main() {
63     test();
64 }

#运行结果

image

 #问题

1.(1)两处

第一处:位于book.hpp中:friend std::ostream& operator<<(std::ostream &out, const Book &book);  用于Book类型;

第二处:位于booksale.hpp中:friend std::ostream& operator<<(std::ostream &out, const BookSale &item);   用于Booksale类型。

(2)

for(auto &record: sales_records) 
cout << record << '\n';

sales_records是类Booksale的容器,record是Booksale类型,此处调用了类Booksale中的重载<<函数;

而类Booksale中的重载<<函数中代码:out << item.rb << '\n'      又调用了类book中的运算符<<的重载函数。

2.(1)

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);

如果bool返回true,x1排在x2前面

如果bool返回false,x1排在x2后面,实现了降序。

(2)sort(sale_records.begin(),sale_records.end(),[](const Booksale &x1,const Booksale &x2){return x1.get_amount>x2.get_amount;});

##实验任务3

#代码:

task3_1.cpp

 1 #include<iostream>
 2  class A
 3  {
 4   public:
 5     A(int x0,int y0);
 6     void display() const;
 7   private:
 8     int x,y;
 9  };
10  A::A(int x0,int y0):x{x0} ,y{y0}
11  {
12   }
13  void A::display() const
14 {
15     std::cout<<x<<", "<<y<<'\n';
16  }
17  class B
18  {
19      public:
20          B(double x0,double y0);
21          void display() const;
22      private:
23         double x,y;
24  };
25  B::B(double x0,double y0):x{x0},y{y0}
26  {
27   }
28   void B::display() const
29   {
30       std::cout<<x<<", "<<y<<'\n';
31    }
32   void test()
33   {
34       std::cout<<"测试类A:"<<'\n';
35     A a(3,4);
36     a.display();
37     std::cout<<"\n测试类B: "<<'\n';
38     B b(3.2,5.6);
39     b.display();
40    }
41    int main()
42    {
43        test();
44     }

task3_2.cpp

 1 #include<iostream>
 2 #include<string>
 3  template<typename T>
 4  class X
 5  {
 6      public:
 7         X(T x0,T y0);
 8         void display();
 9     private:
10         T x,y;
11  };
12  template<typename T>
13  X<T>::X(T x0,T y0):x{x0},y{y0}
14  {
15  }
16  template<typename T>
17  void X<T>::display()
18  {
19   std::cout << x << ", " << y << '\n';
20 }
21  void test()
22  {
23      std::cout << "测试1: 用int实例化类模板X" << '\n';
24     X<int> x1(3, 4);
25     x1.display();
26     std::cout << "\n测试2: 用double实例化类模板X" << '\n';
27     X<double> x2(3.2, 5.6);
28     x2.display();
29     std::cout << "\n测试3: 用string实例化类模板X" << '\n';
30     X<std::string> x3("hello", "oop");
31     x3.display();
32  }
33  int main()
34  {
35      test();
36  }

#运行结果

image

 

image

 ##实验任务4

#代码

Pet.hpp

 1 #pragma
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 // 抽象基类:机器宠物
 7 class MachinePet {
 8 protected:
 9     std::string nickname;  // 昵称
10 
11 public:
12     // 构造函数:用字符串初始化昵称
13     MachinePet(const std::string& name) : nickname(name) {}
14     
15     // 虚析构函数,确保正确的资源释放
16     virtual ~MachinePet() {}
17     
18     // 供外部获取昵称
19     std::string get_nickname() const {
20         return nickname;
21     }
22     
23     // 纯虚函数:返回叫声,支持运行时多态
24     virtual std::string talk() const = 0;
25 };
26 
27 // 电子宠物猫类
28 class PetCat : public MachinePet {
29 public:
30     // 构造函数:用字符串初始化昵称
31     PetCat(const std::string& name) : MachinePet(name) {}
32     
33     // 实现talk(),返回猫叫声
34     std::string talk() const override {
35         return "Meow! Meow!";
36     }
37 };
38 
39 // 电子宠物狗类
40 class PetDog : public MachinePet {
41 public:
42     // 构造函数:用字符串初始化昵称
43     PetDog(const std::string& name) : MachinePet(name) {}
44     
45     // 实现talk(),返回狗叫声
46     std::string talk() const override {
47         return "Woof! Woof!";
48     }
49 };

task4.cpp

 1 #include <iostream>
 2 #include <memory>
 3 #include <vector>
 4 #include "pet.hpp"
 5 
 6 void test1() {
 7     std::vector<MachinePet *> pets;
 8 
 9     pets.push_back(new PetCat("miku"));
10     pets.push_back(new PetDog("da huang"));
11 
12     for(MachinePet *ptr: pets) {
13         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
14         delete ptr;  // 须手动释放资源
15     }   
16 }
17 
18 void test2() {
19     std::vector<std::unique_ptr<MachinePet>> pets;
20 
21     pets.push_back(std::make_unique<PetCat>("miku"));
22     pets.push_back(std::make_unique<PetDog>("da huang"));
23 
24     for(auto const &ptr: pets)
25         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
26 }
27 
28 void test3() {
29     // MachinePet pet("little cutie");   // 编译报错:无法定义抽象类对象
30 
31     const PetCat cat("miku");
32     std::cout << cat.get_nickname() << " says " << cat.talk() << '\n';
33 
34     const PetDog dog("da huang");
35     std::cout << dog.get_nickname() << " says " << dog.talk() << '\n';
36 }
37 
38 int main() {
39     std::cout << "测试1: 使用原始指针\n";
40     test1();
41 
42     std::cout << "\n测试2: 使用智能指针\n";
43     test2();
44 
45     std::cout << "\n测试3: 直接使用类\n";
46     test3();
47 }

#运行结果

image

 ##实验任务5

#代码

Complex.hpp

 1 #pragma
 2 
 3 #include <iostream>
 4 
 5 // 复数类模板
 6 template<typename T>
 7 class Complex {
 8 private:
 9     T real;      // 实部
10     T imag;      // 虚部
11 
12 public:
13     // 默认构造函数
14     Complex() : real(0), imag(0) {}
15     
16     // 带参数构造函数
17     Complex(T r, T i = 0) : real(r), imag(i) {}
18     
19     // 拷贝构造函数
20     Complex(const Complex<T>& other) : real(other.real), imag(other.imag) {}
21     
22     // 获取实部
23     T get_real() const {
24         return real;
25     }
26     
27     // 获取虚部 - 注意:测试代码中用的是get_imag()而不是get_image()
28     T get_imag() const {
29         return imag;
30     }
31     
32     // 设置实部
33     void set_real(T r) {
34         real = r;
35     }
36     
37     // 设置虚部
38     void set_imag(T i) {
39         imag = i;
40     }
41     
42     // 重载 += 运算符
43     Complex<T>& operator+=(const Complex<T>& other) {
44         real += other.real;
45         imag += other.imag;
46         return *this;
47     }
48     
49     // 重载 + 运算符
50     Complex<T> operator+(const Complex<T>& other) const {
51         return Complex<T>(real + other.real, imag + other.imag);
52     }
53     
54     // 重载 == 运算符
55     bool operator==(const Complex<T>& other) const {
56         return (real == other.real) && (imag == other.imag);
57     }
58     
59     // 友元函数:输入运算符
60     template<typename U>
61     friend std::istream& operator>>(std::istream& is, Complex<U>& c);
62     
63     // 友元函数:输出运算符
64     template<typename U>
65     friend std::ostream& operator<<(std::ostream& os, const Complex<U>& c);
66 };
67 
68 // 重载输入运算符
69 template<typename T>
70 std::istream& operator>>(std::istream& is, Complex<T>& c) {
71     T r, i;
72     is >> r >> i;  // 输入格式:实部 虚部
73     c.real = r;
74     c.imag = i;
75     return is;
76 }
77 
78 // 重载输出运算符
79 template<typename T>
80 std::ostream& operator<<(std::ostream& os, const Complex<T>& c) {
81     os << c.real;
82     if (c.imag >= 0) {
83         os << "+" << c.imag << "i";
84     } else {
85         os << c.imag << "i";  // 负数自带负号
86     }
87     return os;
88 }

task5.cpp

 1 #include <iostream>
 2 #include "Complex.hpp"
 3 
 4 void test1() {
 5     using std::cout;
 6     using std::boolalpha;
 7     
 8     Complex<int> c1(2, -5), c2(c1);
 9 
10     cout << "c1 = " << c1 << '\n';
11     cout << "c2 = " << c2 << '\n';
12     cout << "c1 + c2 = " << c1 + c2 << '\n';
13     
14     c1 += c2;
15     cout << "c1 = " << c1 << '\n';
16     cout << boolalpha << (c1 == c2) << '\n';
17 }
18 
19 void test2() {
20     using std::cin;
21     using std::cout;
22 
23     Complex<double> c1, c2;
24     cout << "Enter c1 and c2: ";
25     cin >> c1 >> c2;
26     cout << "c1 = " << c1 << '\n';
27     cout << "c2 = " << c2 << '\n';
28 
29     const Complex<double> c3(c1);
30     cout << "c3.real = " << c3.get_real() << '\n';
31     cout << "c3.imag = " << c3.get_imag() << '\n';
32 }
33 
34 int main() {
35     std::cout << "自定义类模板Complex测试1: \n";
36     test1();
37 
38     std::cout << "\n自定义类模板Complex测试2: \n";
39     test2();
40 }

#运行结果

image

 

posted @ 2025-12-16 20:54  xzhls  阅读(3)  评论(0)    收藏  举报