实验五
任务1:

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

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

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


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

任务3

任务4

#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

#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();
}
浙公网安备 33010602011771号