实验5

实验任务1:

源代码:

点击查看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';
}
点击查看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;      // 音乐艺术家名称
};
点击查看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();
}
运行截图:

wps (1)
问题1:
(1)纯虚函数,virtual void publish() const = 0。
(2)不能,因为Publisher是抽象类。
问题2:
(1)纯虚函数,void publish() const override和void use() const override。
(2)如图:
wps

问题3
(1)基类指针。
(2)Book、Film、Music。
(3)为了实现 “析构多态”避免内存泄漏,派生类的成员无法被正确释放,导致内存泄漏。

实验任务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"
// 图书销售记录类BookSale:声明
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"
// 图书销售记录类BookSale:实现
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 "booksale.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// 按图书销售数额比较(降序)
bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
    return x1.get_amount() > x2.get_amount();
}
void test() {
    using namespace std;
    vector<BookSale> sales_lst; // 存放图书销售记录
    int books_number;
    cout << "录入图书数量: ";
    cin >> books_number;
    cout << "录入图书销售记录" << endl;
    for (int i = 0; i < books_number; ++i) {
        string name, author, translator, isbn;
        float price;
        cout << string(20, '-') << "第" << i + 1 << "本图书信息录入" << string(20, '-') << endl;
        cout << "录入书名: ";
        cin >> name;
        cout << "录入作者: ";
        cin >> author;
        cout << "录入译者: ";
        cin >> translator;
        cout << "录入isbn: ";
        cin >> isbn;
        cout << "录入定价: ";
        cin >> price;
        Book book(name, author, translator, isbn, price);
        float sales_price;
        int sales_amount;
        cout << "录入售价: ";
        cin >> sales_price;
        cout << "录入销售数量: ";
        cin >> sales_amount;
        BookSale record(book, sales_price, sales_amount);
        sales_lst.push_back(record);
    }
    // 按销售册数降序排序
    sort(sales_lst.begin(), sales_lst.end(), compare_by_amount);
    // 按销售册数降序输出图书销售信息
    cout << string(20, '=') << "图书销售统计" << string(20, '=') << endl;
    for (auto &t : sales_lst) {
        cout << t << endl;
        cout << string(40, '-') << endl;
    }
}
int main() {
    test();
}
运行截图

wps (2)

问题1
(1) 被重载了 2 处,分别用于Book类和BookSale类。
(2)cout << item.rb << '\n'和cout << t << endl。
问题2
(1)先定义比较函数compare_by_amount,返回x1.get_amount() > x2.get_amount(),实现销售数量降序逻辑。调用标准库sort函数,传入容器首尾迭代器sales_lst.begin()和sales_lst.end(),并指定比较函数compare_by_amount,完成排序。

实验任务3

实验任务4

补全代码

点击查看pet.hpp
#pragma once
#include <string>
// 机器宠物抽象类(MachinePet)
class MachinePet {
public:
    // 构造函数:用字符串初始化昵称
    MachinePet(const std::string& nickname_) : nickname(nickname_) {}  
    // 虚析构函数:确保派生类对象正确析构
    virtual ~MachinePet() = default;  
    // 接口:获取昵称
    std::string get_nickname() const {
        return nickname;
    } 
    // 纯虚函数:叫声接口(运行时多态,派生类实现)
    virtual std::string talk() const = 0;
protected:
    std::string nickname; // 机器宠物昵称
};
// 电子宠物猫类(PetCat):公有继承自MachinePet
class PetCat : public MachinePet {
public:
    // 构造函数:初始化昵称(通过初始化列表传递给基类)
    PetCat(const std::string& nickname_) : MachinePet(nickname_) {}   
    // 实现talk():返回猫叫声
    std::string talk() const override {
        return "miao wu~";
    }
};
// 电子宠物狗类(PetDog):公有继承自MachinePet
class PetDog : public MachinePet {
public:
    // 构造函数:初始化昵称(通过初始化列表传递给基类)
    PetDog(const std::string& nickname_) : MachinePet(nickname_) {} 
    // 实现talk():返回狗叫声
    std::string talk() const override {
        return "wang wang~";
    }
};
点击查看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();
}
运行截图:

屏幕截图 2025-12-14 223013

实验任务5

完整代码

点击查看Complex.hpp
#pragma once
#include <iostream>

// 复数类模板Complex
template<typename T>
class Complex {
public:
    // 1. 构造函数(支持默认构造、带参构造、拷贝构造)
    Complex() : real(0), imag(0) {}  // 默认构造:实部虚部均为0
    Complex(T r, T i) : real(r), imag(i) {}  // 带参构造:初始化实部和虚部
    Complex(const Complex<T>& other) : real(other.real), imag(other.imag) {}  // 拷贝构造
    // 2. 接口:获取实部和虚部
    T get_real() const { return real; }
    T get_imag() const { return imag; }
    // 3. 运算符重载:+=(成员函数,支持复数相加)
    Complex<T>& operator+=(const Complex<T>& rhs) {
        this->real += rhs.real;
        this->imag += rhs.imag;
        return *this;
    }
    // 4. 运算符重载:==(成员函数,判断复数相等)
    bool operator==(const Complex<T>& rhs) const {
        return (this->real == rhs.real) && (this->imag == rhs.imag);
    }
    // 5. 友元函数:重载<<(输出复数,格式:实部±虚部i)
    friend 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;
    }
    // 6. 友元函数:重载>>(输入复数,支持两种输入格式:a b 或 a±bi)
    friend std::istream& operator>>(std::istream& in, Complex<T>& c) {
        in >> c.real >> c.imag;
        return in;
    }
private:
    T real;  // 复数实部
    T imag;  // 复数虚部
};
// 7. 运算符重载:+(非成员函数,支持复数+复数)
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());
}
点击查看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();
}

运行截图:

屏幕截图 2025-12-14 223949

posted @ 2025-12-14 22:40  王扁  阅读(3)  评论(0)    收藏  举报