NUIST-OOP-LAB05
实验5-多态
实验目的
- 知道什么是类模板,会正确定义和实例化
- 理解运算符重载机制,会编写运算符函数,理解编译器如何将表达式转换为对运算符函数的调用
- 知道什么是抽象类,会正确定义和使用
- 基于问题场景,能合理使用继承、虚函数、抽象类实现接口继承与运行时多态
实验准备
系统浏览/复习以下教材章节:
- 继承:解决的问题场景、定义和用法(第7章)
- 多态:概念、分类、典型应用场景和用法(第8章)
- 类模板(9.1.2节)
实验结论
实验1
验证性实验。综合应用组合、继承、多态实现出版物的分类管理。运行、理解代码,回答问题。
- 问题场景描述
模拟出版物的分类管理。抽象设计后,继承关系如下:
![image]()
- 代码组织
- publisher.hpp类 Publisher 及其派生类 Book , Film , Music 声明
- publisher.cpp类 Publisher 及其派生类 Book , Film , Music 实现
- task1.cpp测试模块 + main
#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';
}
#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; // 音乐艺术家名称
};
#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();
}

Q1:
- 是否包含纯虚函数
![image]()
- 不能,不能实例化抽象函数
Q2: ![image]()
![image]()
Q3:- 声明类型:Publisher*
- Book, Film, Music
- 需要保证析构的时候即析构基类对象,也能析构继承的对象;如果删除virtual标签并delete对应类型的指针,将导致只有基类的析构函数执行了,而子类的析构函数没有执行
实验任务2
验证性实验。综合应用运算符重载、组合、标准库实现图书销售统计。
- 问题场景描述
模拟出版行业图书销售统计,按指定关键字做销量统计、排序。 - 代码组织
- book.hpp图书描述信息类Book声明
- book.cpp图书描述信息类Book实现
- booksale.hpp图书销售记录类BookSale声明
- booksale.cpp图书销售记录类BookSale实现
- task2.cpp 测试模块 + main
#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; // 定价
};
#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;
}
#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; // 销售数量
};
#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;
}
#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();
}

Q1
- 2处,用于Book类型和Booksale类型,
![image]()
Q2- sort函数接受了vector类sales_record的迭代器,并手动提供了一个谓词函数从而实现
![image]()
实验任务3
验证性实验:类模板定义和使用。阅读、理解代码,结合运行回答问题。
问题场景描述
类A和类B除数据成员类型不同,其它都相同。类定义存在相似性
把类型参数化,让类的抽象设计更通用。代码组织
task3_1.cpp 类A定义 + 类B定义 + 测试模块 + main
task3_2.cpp 类模板X定义 + 测试模块 + main
#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();
}

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

实验任务4
设计性实验。综合应用继承、多态,模拟简单机器宠物。
问题场景描述
模拟机器宠物,抽象后,继承关系如下:

定义抽象类:机器宠物类 MachinePet
每个机器宠物包含如下成员:
数据:昵称(nickname)
接口要求
构造函数:用字符串初始化昵称
get_nickname() :供外部获取昵称talk() :返回叫声,须支持运行时多态(由派生类各自实现)。
定义电子宠物猫类 PetCat
公有继承自 MachinePet
无新增数据
构造函数:用字符串初始化昵称
实现 talk() 返回猫叫声
定义电子宠物狗类 PetDog
公有继承自 MachinePet
无新增数据
构造函数:用字符串初始化昵称
实现 talk() 返回狗叫声
代码组织
pet.hpp 机器宠物抽象类 MachinePet 、宠物猫类 PetCat 、宠物狗类 PetDog 定义
task4.cpp 测试模块 + main
#ifndef PET_HPP
#define PET_HPP
#include <string>
class MachinePet {
public:
explicit MachinePet(const std::string &name) : nickname(name) {}
virtual ~MachinePet() = default;
std::string get_nickname() const { return nickname; }
virtual std::string talk() const = 0;
protected:
std::string nickname;
};
class PetCat : public MachinePet {
public:
explicit PetCat(const std::string &name) : MachinePet(name) {}
std::string talk() const override { return "wu~"; }
};
class PetDog : public MachinePet {
public:
explicit PetDog(const std::string &name) : MachinePet(name) {}
std::string talk() const override { return "wang wang~"; }
};
#endif // PET_HPP
#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();
}

实验任务5
设计性实验。综合应用运算符重载、类模板实现编译时多态。
问题场景描述
自定义简化版类模板 Complex , 实现类似C++标准库类模板 complex ,支持对类型的参数化。具体要求如下:
支持实例化类模板与各种构造
如 Complex
提供接口 get_real() , get_image() 返回实部和虚部
对类模板重载运算符,支持如下操作: c1 += c2 , c1 + c2 , c1 == c2 , cin >> c1 >> c2 , cout
<< c1 << c2
代码组织
Complex.hpp类模板 Complex 定义
task5.cpp测试模块 + main
测试代码task5.cpp已给出。根据测试代码,补足类模板 Complex 定义,使代码运行后满足预期截图效果。
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <iostream>
template <typename T>
class Complex {
public:
Complex() : real_(0), imag_(0) {}
Complex(T real, T imag = 0) : real_(real), imag_(imag) {}
Complex(const Complex &other) = default;
T get_real() const { return real_; }
T get_imag() const { return imag_; }
Complex &operator+=(const Complex &other) {
real_ += other.real_;
imag_ += other.imag_;
return *this;
}
friend Complex operator+(Complex lhs, const Complex &rhs) {
lhs += rhs;
return lhs;
}
friend bool operator==(const Complex &lhs, const Complex &rhs) {
return lhs.real_ == rhs.real_ && lhs.imag_ == rhs.imag_;
}
friend std::istream &operator>>(std::istream &in, Complex &c) {
T r{}, i{};
if (in >> r >> i) {
c.real_ = r;
c.imag_ = i;
}
return in;
}
friend std::ostream &operator<<(std::ostream &out, const Complex &c) {
out << c.real_ << (c.imag_ < 0 ? " - " : " + ")
<< (c.imag_ < 0 ? -c.imag_ : c.imag_) << 'i';
return out;
}
private:
T real_;
T imag_;
};
#endif // COMPLEX_HPP
#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();
}








浙公网安备 33010602011771号