实验五

任务一

 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.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

image

回答问题:

问题1:抽象类机制 (1) 是因为 Publisher 类包含纯虚函数,具体依据是 virtual void publish() const = 0;virtual void use() const = 0;。 (2) 不能编译通过。因为 Publisher 是抽象类,不能实例化。

问题2:纯虚函数与接口继承 (1) Book、Film、Music 必须实现 void publish() constvoid use() const 两个函数。

完整函数声明:

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

(2) 如果在 Publisher.cpp 的 Film 类实现中去掉 const,重新编译,报错信息为:

error: candidate function not viable: 'const' qualifier on member function does not match original declaration

问题3:运行时多态与虚析构 (1) for(Publisher*ptr: v) 中 ptr 的声明类型是 Publisher*。 (2) 当循环执行到 ptr->publish(); 时,ptr 实际指向的对象类型依次为:Book、Film、Music。 (3) 基类 Publisher 的析构函数声明为 virtual 是为了确保在删除派生类对象时,能够正确调用派生类的析构函数。若删除 virtual,执行 delete ptr; 会只调用基类的析构函数,而不会调用派生类的析构函数,可能导致资源泄漏。

 任务二

#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
#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 "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
#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
 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

image

回答问题:

问题1:重载运算符<< (1) 运算符<<被重载了2处,分别用于 Book 和 BookSale 类型。 (2) 使用重载<<输出对象的代码:

cpp
编辑
cout << t << endl;

问题2:图书销售统计 (1) "按销售数量降序排序"的实现方式是使用 sort(sales_lst.begin(), sales_lst.end(), compare_by_amount);,其中 compare_by_amount 函数返回 x1.get_amount() > x2.get_amount(),即按销售数量降序排序。 (2) 拓展:使用 lambda 表达式实现:

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

image

image

 任务四

 1 #pragma once
 2 #include <string>
 3 
 4 class MachinePet {
 5 public:
 6     MachinePet(const std::string& nickname_);
 7     virtual ~MachinePet() = default;
 8     std::string get_nickname() const;
 9     virtual std::string talk() const = 0; // 纯虚函数
10 protected:
11     std::string nickname;
12 };
13 
14 class PetCat : public MachinePet {
15 public:
16     PetCat(const std::string& nickname_);
17     std::string talk() const override;
18 };
19 
20 class PetDog : public MachinePet {
21 public:
22     PetDog(const std::string& nickname_);
23     std::string talk() const override;
24 };
pet.hpp
 1 #include <iostream>
 2 #include <memory>
 3 #include <vector>
 4 #include "pet.hpp"
 5 
 6 // 实现放在同一文件或单独 cpp 中
 7 MachinePet::MachinePet(const std::string& nickname_) : nickname(nickname_) {}
 8 std::string MachinePet::get_nickname() const { return nickname; }
 9 
10 PetCat::PetCat(const std::string& nickname_) : MachinePet(nickname_) {}
11 std::string PetCat::talk() const { return "miao wu-"; }
12 
13 PetDog::PetDog(const std::string& nickname_) : MachinePet(nickname_) {}
14 std::string PetDog::talk() const { return "wang wang~"; }
15 
16 void test1() {
17     std::vector<MachinePet*> pets;
18     pets.push_back(new PetCat("miku"));
19     pets.push_back(new PetDog("da huang"));
20 
21     for (MachinePet* ptr : pets) {
22         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
23         delete ptr;
24     }
25 }
26 
27 void test2() {
28     std::vector<std::unique_ptr<MachinePet>> pets;
29     pets.push_back(std::make_unique<PetCat>("miku"));
30     pets.push_back(std::make_unique<PetDog>("da huang"));
31 
32     for (const auto& ptr : pets) {
33         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
34     }
35 }
36 
37 void test3() {
38     const PetCat cat("miku");
39     std::cout << cat.get_nickname() << " says " << cat.talk() << '\n';
40     const PetDog dog("da huang");
41     std::cout << dog.get_nickname() << " says " << dog.talk() << '\n';
42 }
43 
44 int main() {
45     std::cout << "测试1:使用原始指针\n";
46     test1();
47     std::cout << "\n测试2:使用智能指针\n";
48     test2();
49     std::cout << "\n测试3:直接使用类\n";
50     test3();
51 }
task4.cpp

image

 任务五

 1 #pragma once
 2 #include <iostream>
 3 
 4 template<typename T>
 5 class Complex {
 6 public:
 7     Complex(T real_ = 0, T imag_ = 0);
 8     Complex(const Complex& other);
 9     T get_real() const;
10     T get_imag() const;
11     Complex& operator+=(const Complex& other);
12     friend std::ostream& operator<<(std::ostream& out, const Complex& c) {
13         out << c.real << (c.imag >= 0 ? " + " : " - ") << std::abs(c.imag) << "i";
14         return out;
15     }
16     friend std::istream& operator>>(std::istream& in, Complex& c) {
17         in >> c.real >> c.imag;
18         return in;
19     }
20 private:
21     T real, imag;
22 };
23 
24 template<typename T>
25 Complex<T>::Complex(T real_, T imag_) : real(real_), imag(imag_) {}
26 
27 template<typename T>
28 Complex<T>::Complex(const Complex& other) : real(other.real), imag(other.imag) {}
29 
30 template<typename T>
31 T Complex<T>::get_real() const { return real; }
32 
33 template<typename T>
34 T Complex<T>::get_imag() const { return imag; }
35 
36 template<typename T>
37 Complex<T>& Complex<T>::operator+=(const Complex& other) {
38     real += other.real;
39     imag += other.imag;
40     return *this;
41 }
42 
43 template<typename T>
44 Complex<T> operator+(const Complex<T>& a, const Complex<T>& b) {
45     return Complex<T>(a.get_real() + b.get_real(), a.get_imag() + b.get_imag());
46 }
47 
48 template<typename T>
49 bool operator==(const Complex<T>& a, const Complex<T>& b) {
50     return a.get_real() == b.get_real() && a.get_imag() == b.get_imag();
51 }
Complex
 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

 

image

 

posted @ 2025-12-16 22:34  KXJSLL  阅读(4)  评论(0)    收藏  举报