实验5

Task1

源代码

Publisher.h
#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.h"

// 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.h"
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();
}

运行截图

task1(1)

问题

问题1:抽象类机制
(1)是什么决定了 Publisher 是抽象类?用一句话说明,并指出代码中的具体依据。
(2)如果在 main.cpp 里直接写 Publisher p; 能否编译通过?为什么?

(1)Publisher类中含有纯虚函数
	virtual void publish() const = 0; // 纯虚函数,作为接口继承
	virtual void use() const = 0; // 纯虚函数,作为接口继承
(2)不能。Publisher是纯虚函数,不能实例化

问题2:纯虚函数与接口继承
(1) Book 、 Film 、 Music 必须实现哪两个函数才能通过编译?请写出其完整函数声明。
(2) 在 publisher.cpp 的 Film 类实现中,把两个成员函数实现里的 const 去掉(保持函数体不变),重新
编译,报错信息是什么?

(1)实现基类中的纯虚函数
	virtual void publish() const = 0; // 纯虚函数,作为接口继承
	virtual void use() const = 0; // 纯虚函数,作为接口继承
(2)

task1(2)

问题3:运行时多态与虚析构
(1)在 test1() 里, for (Publisher *ptr : v) 中 ptr 的声明类型是什么?
(2)当循环执行到 ptr->publish(); 时, ptr 实际指向的对象类型分别有哪些?(按循环顺序写出)
(3)基类 Publisher 的析构函数为何声明为 virtual ?若删除 virtual ,执行 delete ptr; 会出现什么
问题?

(1)Publisher*
(2)Book Film Music
(3)在派生类的析构函数起作用时,确保能够正确调用相应的析构函数
	不能正确调用相应的析构函数来释放资源,可能会导致内存泄露

Task2

源代码

Book.h
#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; // 定价
};
BookSale.h
#pragma once
#include <string>
#include "Book.h"
// 图书销售记录类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; // 销售数量
};
Book.cpp
#include <iomanip>
#include <iostream>
#include <string>
#include "Book.h"
// 图书描述信息类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.cpp
#include <iomanip>
#include <iostream>
#include <string>

#include "BookSale.h"

// 图书销售记录类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 "BookSale.h"
#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();
}

运行截图

task2

问题

问题1:重载运算符<<
(1)找出运算符 << 被重载了几处?分别用于什么类型?
(2)找出使用重载 << 输出对象的代码,写在下面。

(1)两次
第一次,Book.h文件中:
		friend std::ostream& operator<<(std::ostream& out, const Book& book);
		用于Book类
第二次,BookSale.h文件中:
		friend std::ostream& operator<<(std::ostream& out, const BookSale& item);
		用于BookSale类
(2)cout << t << endl;

问题2:图书销售统计
(1)图书销售记录"按销售数量降序排序",代码是如何实现的?
(2)拓展(选答*):如果使用lambda表达式,如何实现"按销售数量降序排序"?

(1)通过sort(sales_lst.begin(), sales_lst.end(), compare_by_amount);语句
从sales_lst.begin()到sales_lst.end(),依次调用compare_by_amount()函数

Task4

源代码

Pet.h
#pragma once

#include <iostream>
#include <string> 

class MachinePet
{
public:
    std::string get_nickname() const;
    virtual std::string talk() const = 0;

    MachinePet(std::string name_);
    virtual ~MachinePet() = 0; 
private:
    std::string nickname;
};

class PetCat : public MachinePet {
public:
    std::string talk() const override;
    PetCat(std::string name_);
};

class PetDog : public MachinePet {
public:
    std::string talk() const override;
    PetDog(std::string name_) : MachinePet(name_) {}
};
Pet.cpp
#include "Pet.h"

std::string MachinePet::get_nickname() const {
    return nickname;
}

MachinePet::MachinePet(std::string name_) : nickname{ name_ } {}

MachinePet::~MachinePet() {}

std::string PetCat::talk() const {
    return "miao wu~";
}

PetCat::PetCat(std::string name_) : MachinePet(name_) {}

std::string PetDog::talk() const {
    return "wang wang~";
}
task4.cpp
#include <iostream>
#include <memory>
#include <vector>
#include "Pet.h"
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();
}

运行截图

task4

Task5

源代码

Complex.h
#pragma once

#include <iostream>
#include <cmath>

template<typename T>
class Complex{
public:
	Complex(T real_ = 0, T imag_ = 0);
	Complex(const Complex<T>& other);

	T get_real() const;
	T get_imag() const;

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

    Complex<T> operator+(const Complex<T>& other) const {
        Complex<T> temp = *this;
        temp += other;
        return temp;
    }

    bool operator==(const Complex<T>& other) const {
        return (real == other.real) && (imag == other.imag);
    }

    // 声明友元:让全局<<能访问私有成员
    friend std::ostream& operator<<(std::ostream& out, const Complex<T>& c) {
        out << c.real
            << (c.imag >= 0 ? " + " : " - ")
            << std::abs(c.imag) << "i";  // 用abs避免负负得正
        return out;
    }

    // 声明友元:让全局>>能访问私有成员
    friend std::istream& operator>>(std::istream& in, Complex<T>& c) {
        in >> c.real >> c.imag;
        return in;
    }

private:
	T real, imag;
};

template<typename T>
Complex<T>::Complex(T real_, T imag_) :real{ real_ }, imag{ imag_ } {}

template<typename T>
Complex<T>::Complex(const Complex<T>& other)
    : real(other.real), imag(other.imag) {
}

template<typename T>
T Complex<T>::get_imag() const {
    return imag;
}

template<typename T>
T Complex<T>::get_real() const {
    return real;
}


task5
#pragma once

#include <iostream>
#include <cmath>

template<typename T>
class Complex{
public:
	Complex(T real_ = 0, T imag_ = 0);
	Complex(const Complex<T>& other);

	T get_real() const;
	T get_imag() const;

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

    Complex<T> operator+(const Complex<T>& other) const {
        Complex<T> temp = *this;
        temp += other;
        return temp;
    }

    bool operator==(const Complex<T>& other) const {
        return (real == other.real) && (imag == other.imag);
    }

    // 声明友元:让全局<<能访问私有成员
    friend std::ostream& operator<<(std::ostream& out, const Complex<T>& c) {
        out << c.real
            << (c.imag >= 0 ? " + " : " - ")
            << std::abs(c.imag) << "i";  // 用abs避免负负得正
        return out;
    }

    // 声明友元:让全局>>能访问私有成员
    friend std::istream& operator>>(std::istream& in, Complex<T>& c) {
        in >> c.real >> c.imag;
        return in;
    }

private:
	T real, imag;
};

template<typename T>
Complex<T>::Complex(T real_, T imag_) :real{ real_ }, imag{ imag_ } {}

template<typename T>
Complex<T>::Complex(const Complex<T>& other)
    : real(other.real), imag(other.imag) {
}

template<typename T>
T Complex<T>::get_imag() const {
    return imag;
}

template<typename T>
T Complex<T>::get_real() const {
    return real;
}


运行截图

task5

posted @ 2025-12-14 20:57  永和九年2  阅读(6)  评论(0)    收藏  举报