实验5 多态

实验任务1

实验代码:

publisher.hpp:

#pragma once
#include <string>

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

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

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(const std::string& name_) : name{ name_ } {
}

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

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

运行测试截图:
image
回答问题:

问题1:

(1)Publisher中包含纯虚函数,因此它是抽象类

依据:

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

(2)不能编译通过,抽象类不能直接实例化对象,只能作为基类被继承

问题2:

(1)publisher函数,use函数

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

(2)
image

问题3:

(1) ptr的声明类型是Publisher*

(2) 实际指向的类型是Book,Film,Music

(3) 确保通过基类指针删除子类对象时,能正确调用子类的析构函数
删除virtual后,执行delete ptr,仅调用基类Publisher的析构函数,子类的析构函数不会调用,导致内存泄漏

实验任务2

实验代码:

book.hpp:

#pragma once
#include <string>

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;
	double price;
};

book.cpp:

#include <iomanip>
#include <iostream>
#include <string>
#include "book.hpp"

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"

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

运行测试截图:
image
回答问题:

问题1:

(1)代码中重载了2次 << 运算符
第一次:在 book.cpp 中,重载 std::ostream& operator<<(std::ostream &out, const Book &book) ,用于输出 Book 类对象
第二次:在 booksale.cpp 中,重载 std::ostream& operator<<(std::ostream &out, const BookSale &item) ,用于输出 BookSale 类对象

(2)

cout << string(20, '=') << "图书销售统计" << string(20, '=') << endl;
for (auto& t : sales_lst) {
	cout << t << endl;
	cout << string(40, '-') << endl;
}

问题2:

(1)代码中通过自定义比较函数 compare_by_amount  和 sort 算法实现:
销售数量大的排前面

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

再调用 sort 函数对 sales_list 排序

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

实验任务4

实验代码:

pet.hpp:

#pragma once

#include<iostream>
#include<string>

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


class PetCat : public MachinePet {
public:
	PetCat(const std::string& name_ = "") :MachinePet{ name_ } {};
	std::string talk() const override {
		return "mi mi mi mi mi";
	}
};

class PetDog : public MachinePet {
public:
	PetDog(const std::string& name_ = "") :MachinePet{ name_ } {};
	std::string talk() const override {
		return "ga ga ga ga ga";
	}
};

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

运行测试截图:
image

实验任务5:

实验代码:

Complex.hpp:

#pragma once

#include <iostream>
#include <string>

template<typename T>
class Complex {
public:
    Complex() : real{ 0 }, imag{ 0 } {};
    Complex(T a, T b) : real{ a }, imag{ b } {};
    Complex(const Complex<T>& other) : real{ other.real }, imag{ other.imag } {};
    T get_real() const { return real; };
    T get_imag() const { return 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);

    friend Complex<T> operator+(const Complex<T>& c1, const Complex<T>& c2) {
        return Complex<T>(c1.real + c2.real, c1.imag + c2.imag);
    }

    Complex<T>& operator+=(const Complex<T>& C);
    bool operator==(const Complex<T>& C) const;

private:
    T real, imag;
};

template<typename T>
std::ostream& operator<<(std::ostream& out, const Complex<T>& C) {
    if (C.imag >= 0)
        out << C.real << '+' << C.imag << 'i';
    else
        out << C.real << C.imag << 'i';
    return out;
}

template<typename T>
std::istream& operator>>(std::istream& in, Complex<T>& C) {
    in >> C.real >> C.imag;
    return in;
}

template<typename T>
Complex<T>& Complex<T>::operator+=(const Complex<T>& C) {
    real += C.real;
    imag += C.imag;
    return *this;
}

template<typename T>
bool Complex<T>::operator==(const Complex<T>& C) const {
    return (real == C.real) && (imag == C.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();
}

运行测试截图:
image

posted @ 2025-12-16 21:18  l栗l  阅读(3)  评论(0)    收藏  举报