实验5 多态

实验任务1

 

代码组织:

publisher.hpp 类publisher及其派生类book,film,music声明
publisher.cpp 类publisher及其派生类book,film,music实现
task1.cpp 测试模块+main
 
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();
}

 
运行测试结果如下:

屏幕截图 2025-12-10 082755

问题1(1):publisher类将成员函数声明为了纯虚函数。代码依据:

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

(2):不能通过编译,抽象类不支持声明对象,类的成员函数没有声明会导致链接错误,纯虚函数的声明允许这条声明没有对应的实现,将类变为抽象类,但尝试声明抽象类对象会直接导致编译错误。
问题2(1):publisher的3个派生类必须实现:

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

(2):报错信息如下:

屏幕截图 2025-12-10 090537

问题3(1):ptr的类型是publisher抽象类的指针型变量
(2):->Book->Film->Music
(3):将基类析构函数声明为virtual,保证在析构时使用派生类对象自己的析构函数而非基类的析构函数,否则delete会使用ptr基类自己的析构函数来释放其指向的派生类对象的内存地址,几乎一定会导致内存泄漏
 

实验任务2

 

代码组织:

book.hpp 图书描述信息类Book声明
book.cpp 图书描述信息类Book实现
booksale.hpp 图书销售记录类BookSale声明
booksale.cpp 图书销售记录类BookSale实现
task2.cpp 测试模块 + main
 
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();
}

 
运行测试结果如下:

屏幕截图 2025-12-11 004144

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

out << item.rb << '\n'...
...
cout << record << '\n';
...

问题2(1):使用标准库的std::sort()函数,在第三个参数中传入自定义的比较函数compare_by_amount来重定义排序标准,以此实现降序的效果
(2):在std::sort()第三个参数传入匿名函数[](const BookSale &x1, const BookSale &x2){return x1.get_amount() > x2.get_amount();}实现按类对象的售价排序
&#nbsp;

实验任务4

 

代码组织:

pet.hpp 机器宠物抽象类MachinePet、宠物猫类PetCat、宠物狗类PetDog定义
task4.cpp 测试模块 + main
 
pet.hpp

#pragma once

#include <string>

class MachinePet {
	protected:
		std::string nickname;
	public:
		MachinePet(const std::string& name): nickname(name) {}
		const std::string& get_nickname() const {return nickname;}
		virtual std::string talk() const = 0;
		virtual ~MachinePet() = default;
};

class PetCat: public MachinePet {
	public:
		PetCat(const std::string& name): MachinePet(name) {}
		std::string talk() const {return "miao wu~";}
};

class PetDog: public MachinePet {
	public:
		PetDog(const std::string& name): MachinePet(name) {}
		std::string talk() const {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-10 233515

 

实验任务5

 

代码组织:

 
Complex.hpp 类模板 Complex定义
task5.cpp 测试模块 + main
 
Complex.hpp

#pragma once

#include <iostream>
#include <cmath>

template<class T>
class Complex {
	private:
		T real, imag;
	public:
		Complex<T>(T _real = 0, T _imag = 0): real(_real), imag(_imag) {}
		Complex<T>(const Complex& other): real(other.real), imag(other.imag) {}
		Complex<T>(Complex&& other) noexcept: real(other.real), imag(other.imag) {}
		
		T get_real() const {return real;}
		T get_imag() const {return imag;}
		Complex<T>& operator+=(const Complex<T>& c) {this->real += c.real; this->imag += c.imag; return *this;}
		Complex<T> operator+(const Complex<T>& c) const {Complex<T>temp(this->real + c.real, this->imag + c.imag); return temp;}
		bool operator==(const Complex<T>& c) const {return this->real == c.real && this->imag == c.imag;}
		
		friend std::istream& operator>>(std::istream& in, Complex<T>& c) {return in >> c.real >> c.imag;}
		friend std::ostream& operator<<(std::ostream& out, const Complex<T>& c) {
			if (c.real < 0) out << "- ";
			out << abs(c.real);
			if (!c.imag) {
				return out;
			} else {
				if (c.imag < 0) out << " - ";
				else out << " + ";
				return out << abs(c.imag) << 'i';
			}
		}		
};

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

 

实验总结:

多态功能的实现由代码层面的模板化template<class T>和类的继承功能来完成,将类,函数的功能由编译时确定转为运行时确定。极大的增加了代码的灵活性和可复用性。需要注意的是,模板化的部分应该为代码不通用的类型重载特殊的具体化,确保功能的完整性,或者明确不会使用这种类型的实例化。继承也可以看作是抽象类的“具体化”,并且这种“具体化”比起模板更加自由,不止在类型层面(派生类与基类类名不同),同时也可以增加具体类自己的特殊成员,扩展数据和功能。

posted @ 2025-12-11 00:55  bastille433  阅读(5)  评论(0)    收藏  举报