实验五

任务1:
631ED1DE43D1F853C1A29EE0F61FC26D
问题1.
(1) Publish存在纯虚函数talk()
(2) 不能,抽象类无法实例化
问题2.
(1) publish和use两个函数,
virtual void publish() = 0 ;
(2)

6B23E70866EFFD17C35417D681D6E16A

问题3. 
    (1) Publish*
    (2) Book,Film,Music
    (3) 无法调用子类的析构函数,只会使用Publish的析构函数,容易引发内存泄漏

任务2:

32F5A7EC789D52A8A12B6B870EB31536

问题1:
    (1) 重载了两次,用于Book和BookSale;
    (2) 

5941712C95B354905EABFAE7F29D1980

8142075AF197A6C2046705C48C458618

问题2
    (1) 使用算法库里的sort,传入sales_records的头迭代器和尾迭代器,以及对应的比较方法;
    (2)

73B539EA5B1DF7607E33242486149F28

任务3

100F261AA62D0ACBF5A4BF828DB9713B

任务4

D311B375C97C9F153469FC6FE117AA3B

    #include <iostream>
    #include <string>

    using namespace std;

    class MachinePet {
    public:
        MachinePet(string nickname) : nickname(nickname) {}
        const string get_nickname() const {
            return nickname;
        }
        virtual string talk() const= 0;
    private:
        const string nickname;
    };

    class PetDog : public MachinePet {
    public:
        PetDog(string nickname) : MachinePet(nickname) {}
        string talk() const override {
            return "wang wang";
        }
    };

    class PetCat : public MachinePet {
    public:
        PetCat(string nickname ) : MachinePet(nickname) {}
        string talk() const override {
            return "miao wu";
        }
    };

任务5

BD351CA729291A698376DC1294D16E7E

#include <iostream>
#include <istream>
#include <ostream>

template <typename T>
class Complex;

template <typename T>
std::ostream& operator<<(std::ostream& os, const Complex<T>& com);

template <typename T>
std::istream& operator>>(std::istream& is, Complex<T>& com);

template <typename T>
class Complex {
    friend std::ostream& operator<< <T>(std::ostream& os, const Complex<T>& com);
    friend std::istream& operator>> <T>(std::istream& is, Complex<T>& com);
public:
    Complex() : Complex(0,0){}
    Complex(T r,T i) : real(r),image(i) {} 
    Complex(const Complex& com) : real(com.real),image(com.image){}
    float get_real() const { return real; }
    float get_imag() const { return image; }
private:
    T real;
    T image;
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const Complex<T>& com) {
    os << com.real << " + " << com.image << "i";
    return os;
}

template <typename T>
std::istream& operator>>(std::istream& is, Complex<T>& com) {
    T i,r;
    std::cin >> i >> r;
    com = Complex<T>(i,r);
    return is;
}

template <typename T>
Complex<T> operator+(const Complex<T>& l, const Complex<T>& r) {
    return Complex<T>(l.get_real() + r.get_real(), l.get_imag() + r.get_imag());
}

template <typename T>
Complex<T>& operator+=(Complex<T>& l, const Complex<T>& r) {
    l = l + r;
    return l;
}

template <typename T>
bool operator==(const Complex<T>& l, const Complex<T>& r) {
    return l.get_imag() == r.get_imag() && l.get_real() == r.get_real();
}
posted @ 2025-12-16 21:56  weiy404  阅读(3)  评论(0)    收藏  举报