实验五

实验

#任务1

##代码

#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();
}
publisher.cpp
#pragma once

#include <string>

// 鍙戣/鍑虹増鐗╃被锛歅ublisher 锛堟娊璞$被锛?
class Publisher {
public:
    Publisher(const std::string &name_ = "");            // 鏋勯€犲嚱鏁?
    virtual ~Publisher() = default;

public:
    virtual void publish() const = 0;                 // 绾櫄鍑芥暟锛屼綔涓烘帴鍙g户鎵?
    virtual void use() const = 0;                     // 绾櫄鍑芥暟锛屼綔涓烘帴鍙g户鎵?

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;      // 闊充箰鑹烘湳瀹跺悕绉?
};
publish.hpp
#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();
}
task1.cpp

##运行测试截图

image

 ##问题回答

问题1:(1)纯虚函数。virtual void publish() const = 0; virtual void use() const = 0;

             (2)不能,Publish为抽象类,含纯虚函数,不能实例化对象

问题2:(1)publish()和user()函数。virtual void publish() const = 0; virtual void use() const = 0;

           (2)[Error] candidate is: virtual void Film::publish() const

image

 问题3:(1)Publisher

              (2)Book,Film,Music

              (3)确保通过基类指针删除派生类对象时,会先调用派生类的析构函数,再调用基类的析构函数,实现资源的完整释放

                   不会调用派生类(Book、Film、Music)的析构函数

#任务2

##代码

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


// 鍥句功鎻忚堪淇℃伅绫籅ook: 瀹炵幇
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;
}
book.cpp
#pragma once
#include <string>

// 鍥句功鎻忚堪淇℃伅绫籅ook: 澹版槑
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.hpp
#pragma once

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

// 鍥句功閿€鍞褰曠被BookSales锛氬0鏄?
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.hpp
#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;
}
booksale.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 << "录入书名: "; cin >> name;
        cout << "录入作者: "; cin >> author;
        cout << "录入译者: "; cin >> translator;
        cout << "录入isbn: "; cin >> 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();
}
task2.cpp

##运行测试截图

屏幕截图 2025-12-14 092814

 

 ##问题回答

问题1:(1)2处,Book和BookSales

              (2)

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

问题2:(1)定义bool compare_by_amount(const BookSale &x1,const BookSale &x1),返回x1.get_amount() > x2.get_amount()的结果

#任务3

##代码

 

#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();
}
task3_1.cpp
#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();
}
task3_2.cpp

 

##运行测试截图

image

 

image

 ##问题回答

 

#任务4

##代码

#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();
}
task4.cpp
#pragma once
#include<iostream>
#include<string>

using namespace std;


class MachinePet{
    string nickname;
    public:
        MachinePet(string name=""):nickname{name}{}
        string get_nickname()const{return nickname;}
        virtual string talk()const=0;
};
class PetCat:public MachinePet{
    public:
        PetCat(string &name):MachinePet(){}
        string talk() const;
};
class PetDog:public MachinePet{
    public:
        PetDog(string &name):MachinePet(name){}
        string talk() const;
};
pet.hpp
#include<iostream>
#include<string>
#include"pet.hpp"


string PetCat::talk() const{return "";} 
string PetDog::talk() const{return "";}
pet.cpp

##运行测试截图

image

 

#任务5

##代码

#pragma once
#include <iostream>

template<typename T>
class Complex {
public:
    Complex() : real(0), imag(0) {}
    Complex(T r, T i) : real(r), imag(i) {}
    Complex(const Complex<T>& c) : real(c.real), imag(c.imag) {}

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

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

    friend std::ostream& operator<<(std::ostream& out, const Complex<T>& c) {
        out << c.real << (c.imag >= 0 ? "+" : "") << c.imag << "i";
        return out;
    }

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

private:
    T real; 
    T imag; 
};

template<typename T>
Complex<T> operator+(const Complex<T>& c1, const Complex<T>& c2) {
    Complex<T> temp = c1;
    temp += c2;
    return temp;
}
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();
}
Task.cpp

##运行测试截图

image

 

 
 
posted @ 2025-12-14 16:23  (清风轩  阅读(2)  评论(0)    收藏  举报