实验五

实验五

任务一:

代码部分:

publisher.hpp:
#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.cpp:

#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';
}
task1.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();
}

 结果截图:

 实验五—任务1—结果1

问题回答:

问题1(1):Publisher 是抽象类是因为它包含了至少一个纯虚函数,无法被实例化。

代码依据:在 publisher.hpp 中,Publisher 类中声明了两个纯虚函数:

virtual void publish() const = 0;  
virtual void use() const = 0;

(2):不能编译通过。因为 Publisher 是抽象类(含有纯虚函数),抽象类不能直接实例化对象。编译器会报错提示无法创建抽象类的实例。

问题2(1):必须实现 Publisher 类中的两个纯虚函数:

void publish() const

void use() const

(2):报错结果为函数签名不匹配, Film::publish() 函数在 Film 类的定义里找不到对应的声明

实验五—任务1—结果1

问题3(1):声明类型是Publisher*(Publisher 类型的指针)

(2):按循环顺序,实际指向的对象类型依次是:Book 对象(new Book("Harry Potter", "J.K. Rowling")),Film 对象(new Film("The Godfather", "Francis Ford Coppola")),Music 对象(new Music("Blowing in the wind", "Bob Dylan"))

(3)【1】声明为 virtual是因为 Publisher 是多态基类,需要通过基类指针删除派生类对象。将析构函数声明为 virtual 可以确保通过基类指针删除对象时,能够正确调用派生类的析构函数,实现完整的对象销毁。

【2】如果删除 virtual,析构函数就变成了普通析构函数。当执行 delete ptr; 时:只会调用 Publisher 的析构函数而不会调用派生类(Book、Film、Music)的析构函数,同时导致派生类特有的资源(如成员变量 author、director、artist 等)无法正确释放,还会造成资源泄漏(memory leak)或其他资源管理问题。

 

任务2:

代码部分:

book.hpp:
#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.cpp:
#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;
}
booksale.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.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;
}
task2.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();
}

结果截图:

实验五—任务2—结果

问题回答:

问题1:运算符 << 被重载了2处,
第一处在 book.hpp 和 book.cpp 中:用于输出 Book 类型对象

std::ostream& operator<<(std::ostream &out, const Book &book);

第二处在 booksale.hpp 和 booksale.cpp 中:用于输出 BookSale 类型对象

std::ostream& operator<<(std::ostream &out, const BookSale &item);

使用重载 << 输出对象的代码:

cout << record << '\n';

问题2:

(1)图书销售记录"按销售数量降序排序"的代码实现部分:

定义比较函数:该函数通过 get_amount() 获取销售数量,使用 > 实现降序排列

bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
    return x1.get_amount() > x2.get_amount();
}

调用排序函数:使用标准库的 sort 算法,传入自定义的比较函数 compare_by_amount

sort(sales_records.begin(), sales_records.end(), compare_by_amount);

获取销售数量的实现:提供了获取私有成员 sales_amount 的接口

int BookSale::get_amount() const {
    return sales_amount;
}

(2)使用 lambda 表达式可以简化代码,直接在 sort 调用中定义比较逻辑:

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

 

任务3(观察理解性任务):

代码部分:

task3_1.cpp:
#include <iostream>

// 类A的定义
class A {
public:
    A(int x0, int y0);
    void display() const;

private:
    int x, y;
};

A::A(int x0, int y0): x{x0}, y{y0} {
}

void A::display() const {
    std::cout << x << ", " << y << '\n';
}

// 类B的定义
class B {
public:
    B(double x0, double y0);
    void display() const;

private:
    double x, y;
};

B::B(double x0, double y0): x{x0}, y{y0} {
}

void B::display() const {
    std::cout << x << ", " << y << '\n';
}

void test() {
    std::cout << "测试类A: " << '\n';
    A a(3, 4);
    a.display();

    std::cout << "\n测试类B: " << '\n';
    B b(3.2, 5.6);
    b.display();
}

int main() {
    test();
}
task3_2.cpp:
#include <iostream>
#include <string>

// 定义类模板
template<typename T>
class X{
public:
    X(T x0, T y0);
    void display();

private:
    T x, y;
};

template<typename T>
X<T>::X(T x0, T y0): x{x0}, y{y0} {
}

template<typename T>
void X<T>::display() {
    std::cout << x << ", " << y << '\n';
}


void test() {
    std::cout << "测试1: 用int实例化类模板X" << '\n';
    X<int> x1(3, 4);
    x1.display();

    std::cout << "\n测试2:用double实例化类模板X" << '\n';
    X<double> x2(3.2, 5.6);
    x2.display();

    std::cout << "\n测试3: 用string实例化类模板X" << '\n';
    X<std::string> x3("hello", "oop");
    x3.display();
}

int main() {
    test();
}

结果截图:

实验五—任务3—结果1

实验五—任务3—结果2

 

任务4:

代码部分:

pet.hpp:

#ifndef PET_HPP
#define PET_HPP

#include <string>

// 抽象类:机器宠物类 MachinePet
class MachinePet {
private:
    std::string nickname;  // 昵称

public:
    // 构造函数:用字符串初始化昵称
    MachinePet(const std::string &name) : nickname(name) {}
    
    // 虚析构函数,确保正确释放派生类资源
    virtual ~MachinePet() = default;
    
    // 供外部获取昵称
    std::string get_nickname() const {
        return nickname;
    }
    
    // 纯虚函数:返回叫声,支持运行时多态
    virtual std::string talk() const = 0;
};

// 电子宠物猫类 PetCat
class PetCat : public MachinePet {
public:
    // 构造函数:用字符串初始化昵称
    PetCat(const std::string &name) : MachinePet(name) {}
    
    // 实现 talk() 返回猫叫声
    std::string talk() const override {
        return "meow";
    }
};

// 电子宠物狗类 PetDog
class PetDog : public MachinePet {  // 修正:应该是 PetDog
public:
    // 构造函数:用字符串初始化昵称
    PetDog(const std::string &name) : MachinePet(name) {}
    
    // 实现 talk() 返回狗叫声
    std::string talk() const override {
        return "wang";
    }
};

#endif // PET_HPP
task4.cpp:
#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();
}

结果截图:

实验五—任务4—结果1

 

任务5:
代码部分:

Complex.hpp :
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <iostream>

// 类模板 Complex 定义
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<T>& other) : real(other.real), imag(other.imag) {}  // 拷贝构造函数
    
    // 获取实部和虚部
    T get_real() const { return real; }
    T get_imag() const { return imag; }
    
    // 运算符重载(成员函数版本)
    Complex<T>& operator+=(const Complex<T>& other) {
        real += other.real;
        imag += other.imag;
        return *this;
    }
    
    bool operator==(const Complex<T>& 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>
Complex<T> operator+(const Complex<T>& lhs, const Complex<T>& rhs) {
    return Complex<T>(lhs.get_real() + rhs.get_real(), 
                      lhs.get_imag() + rhs.get_imag());
}

// 输出运算符重载
template<typename T>
std::ostream& operator<<(std::ostream& out, const Complex<T>& c) {
    out << "(" << c.real;
    if (c.imag >= 0) {
        out << "+" << c.imag << "i)";
    } else {
        out << c.imag << "i)";
    }
    return out;
}

// 输入运算符重载
template<typename T>
std::istream& operator>>(std::istream& in, Complex<T>& c) {
    in >> c.real >> c.imag;
    return in;
}

#endif // COMPLEX_HPP
task5.cpp:
#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();
}

结果截图:

实验五—任务5—结果

 

 

 

 
 

 

posted @ 2025-12-17 05:15  栖月水生  阅读(3)  评论(0)    收藏  举报