实验5

一.实验任务1

1.源代码

task1.cpp
Publisher.cpp
Publisher.hpp

 2.运行结果截图

由于DEVC++的版本问题,我无法运行智能指针,所以将智能指针注释化

1

3.问题1

(1)Publisher 类包含纯虚函数,因此是抽象类。
具体依据:在 publisher.hpp 中,Publisher 类声明了两个纯虚函数:
virtual void publish() const = 0;
virtual void use() const = 0;
(2)不能编译通过
原因:抽象类包含纯虚函数,所以不能实例化对象。

4.问题2

(1)void publish() const override;
void use() const override;
(2)报错信息为函数签名与基类中的纯虚函数不匹配

问题2

是因为基类函数声明为 const,而派生类实现没有 const,导致的错误。

5.问题3

(1)声明类型为指向基类的指针:Publisher*
(2)
Book*
Film*
Music*
(3)
声明为 virtual是为了确保当通过基类指针删除派生类对象时,能正确调用派生类的析构函数,从而避免资源泄漏。
若删除 virtual,执行 delete ptr; 会出现只会调用基类的析构函数的现象,这样不会调用派生类的析构函数,导致派生类未被释放,引发内存泄漏。

 二.实验任务2

1.源代码

 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 }
book.cpp
 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.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_}, 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 }
booksale.cpp
 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.hpp
 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 }
task2.cpp

2.运行结果截图

1

3.问题1

(1)共重载了2处:
①用于 Book 类型
位置:book.cpp 中std::ostream& operator<<(std::ostream &out, const Book &book)
②用于 BookSale 类型
位置:booksale.cpp 中std::ostream& operator<<(std::ostream &out, const BookSale &item)
(2)
for(auto &t: sales_list) {
cout << t << endl;
cout << string(40, '-') << endl;
}

4.问题2

(1)实现方式:
①定义比较函数:在 task2.cpp 中定义了函数 compare_by_amount:
bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
return x1.get_amount() > x2.get_amount();
}
该函数可以实现降序排序:返回 true 表示 x1 排在 x2 前面
②调用 std::sort:使用该函数作为比较标准,对 sales_list 排序:
sort(sales_list.begin(), sales_list.end(), compare_by_amount);
③最后,sales_list 中的元素按 sales_amount从大到小排列。

(2)将原来的排序
sort(sales_list.begin(), sales_list.end(), compare_by_amount);
变成这样
sort(sales_list.begin(), sales_list.end(),
[](const BookSale &x1, const BookSale &x2) {
return x1.get_amount() > x2.get_amount();
}
);

三.问题3

1.源代码

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

2.运行结果截图

3.1

3.2

四.实验任务4

1.源代码

 1 #pragma once
 2 #include <string>
 3 #include <iostream>
 4 
 5 //抽象基类:机器宠物
 6 class MachinePet {
 7 public:
 8     MachinePet(const std::string &nickname) : nickname_(nickname) {}
 9     virtual ~MachinePet() = default;
10     std::string get_nickname() const {
11         return nickname_;
12     }
13     virtual std::string talk() const = 0;
14     
15 private:
16     std::string nickname_;  
17 };
18 
19 // 派生类:电子宠物猫
20 class PetCat : public MachinePet {
21 public:
22     PetCat(const std::string &nickname) : MachinePet(nickname) {}
23     virtual std::string talk() const override {
24         return "miao wu-";
25     }
26 };
27 
28 // 派生类:电子宠物狗
29 class PetDog : public MachinePet {
30 public:
31     PetDog(const std::string &nickname) : MachinePet(nickname) {}
32     virtual std::string talk() const override {
33         return "wang wang~";
34     }
35 };
pet.hpp
 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 }
task4.cpp

2.运行结果截图

1

由于DEVC++的版本问题,我无法运行智能指针,所以将智能指针注释化

五.实验任务5

1.源代码

 1 #pragma once
 2 #include <iostream>
 3 #include <type_traits>
 4 
 5 // 复数类
 6 template<typename T>
 7 class Complex {
 8     static_assert(std::is_arithmetic<T>::value, 
 9                   "Complex type must be arithmetic");
10     
11 private:
12     T real_;  
13     T imag_;  
14     
15 public:
16     Complex() : real_(0), imag_(0) {}
17     Complex(T real, T imag) : real_(real), imag_(imag) {}
18     Complex(const Complex<T>& other) : real_(other.real_), imag_(other.imag_) {}
19     T get_real() const { return real_; }
20     T get_imag() const { return imag_; }
21     
22     Complex<T>& operator+=(const Complex<T>& rhs) {
23         real_ += rhs.real_;
24         imag_ += rhs.imag_;
25         return *this;
26     }
27     
28     Complex<T> operator+(const Complex<T>& rhs) const {
29         return Complex<T>(real_ + rhs.real_, imag_ + rhs.imag_);
30     }
31     
32     bool operator==(const Complex<T>& rhs) const {
33         return (real_ == rhs.real_) && (imag_ == rhs.imag_);
34     }
35     
36     friend std::ostream& operator<<(std::ostream& os, const Complex<T>& c) {
37         os << c.real_;
38         if (c.imag_ >= 0) {
39             os << " + " << c.imag_ << "i";
40         } else {
41             os << " - " << -c.imag_ << "i"; 
42         }
43         return os;
44     }
45 
46     friend std::istream& operator>>(std::istream& is, Complex<T>& c) {
47         is >> c.real_ >> c.imag_;
48         return is;
49     }
50 };
Complex.hpp
 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 }
task5.cpp

2.运行结果截图

1

六.收获与疑惑

这次实验让我深刻体会到了C++是强大与复杂并存的。一方面,C++提供了丰富的特性来实现高效、灵活的编程;另一方面,这些特性需要深入理解和正确使用,否则容易出现问题。最大的收获是理解了多态性不仅是语言特性,更是一种设计思想。通过抽象类定义接口,通过模板实现泛型,这些都能让我们写出更加通用、可维护的代码。同时好的设计应该易于扩展,如任务4中增加新宠物类型只需要新增派生类。除此之外,接口设计要考虑使用方便性,如任务5中运算符重载让复数使用更自然。

 

posted @ 2025-12-10 20:39  flower00  阅读(1)  评论(0)    收藏  举报