OPP实验五
任务一、

任务二、


2【 通过sort库函数来实现,其中,写了一个比较函数来作为sort 的参数】

3【通过ChatGPT】

3、任务三、

1 #pragma once 2 #include <string> 3 using namespace std; 4 5 class MachinePets { 6 private: 7 string nickname; 8 public: 9 MachinePets(const string& n): 10 nickname(n) {} 11 string get_nickname () const 12 { return nickname; } 13 virtual string talk() = 0; 14 }; 15 16 class PetCats : public MachinePets { 17 public: 18 PetCats(const string& n): MachinePets(n) {} 19 string talk() { return "meow"; } 20 }; 21 22 class PetDogs : public MachinePets { 23 public: 24 PetDogs(const string& n): MachinePets(n) {} 25 string talk() { return "woof"; } 26 };
任务四、

1 #include <iostream> 2 #include <iomanip> 3 using namespace std; 4 5 class Film 6 { 7 8 string name; 9 string actor; 10 string country; 11 int year; 12 public: 13 friend istream& operator >>(istream &in, Film &film) 14 { 15 cout << "录入片名: "; in >> film.name; 16 cout << "录入导演: "; in >> film.actor; 17 cout << "录入国家: "; in >> film.country; 18 cout << "录入上映年份: "; in >> film.year; 19 20 return in; 21 } 22 friend compare_by_year (); 23 24 int get_year() { return year; } 25 26 friend ostream& operator <<(ostream &out, const Film &film) 27 { 28 out << left; 29 out << setw(15) << "片名:" << film.name << endl 30 << setw(15) << "主演:" << film.actor << endl 31 << setw(15) << "国家:" << film.country << endl 32 << setw(15) << "年份:" << film.year; 33 out<<endl; 34 out<<"----------------------------"; 35 return out; 36 } 37 }; 38 39 bool compare_by_year(Film& f1, Film& f2) 40 { 41 return f1.get_year() < f2.get_year(); 42 }
任务五、

在编写代码时出现了很多的问题,总结一下:
1、在使用模板类的时候,在函数返回值没有添加<>符号、
2、排查最久的问题
friend Complex<T>& operator+(Complex& c1, Complex& c2)
{
c1+=c2;
return c1;
}
这边的三个地方全都需要加应用类型,否则在使用时就会报错,大概是说把Complex<>&变成了Complex ,不可以
我估计大概原因是:
因为我们输入的c1是引用类型,返回值为c1,所以返回值也是&类型
1 #include<iostream> 2 using namespace std; 3 template<typename T> 4 class Complex 5 { 6 private: 7 T real; 8 T imag; 9 public: 10 Complex(T a=0,T b=0):real(a),imag(b){} 11 12 T get_real(){return real;} 13 T get_imag(){return imag;} 14 15 void operator+=(Complex& c) 16 { 17 real+=c.real; 18 imag+=c.imag; 19 } 20 21 friend Complex<T>& operator+(Complex& c1, Complex c2) 22 { 23 c1+=c2; 24 return c1; 25 } 26 friend bool operator==(Complex& c1, Complex& c2) 27 { 28 return c1.real==c2.real&&c1.imag==c2.imag; 29 } 30 31 friend istream& operator>>(istream& in,Complex& c) 32 { 33 in>>c.real>>c.imag; 34 return in; 35 } 36 37 friend ostream& operator<<(ostream& os,Complex& c) 38 { 39 if(c.imag>0) 40 os<<c.real<<"+"<<c.imag<<"i"; 41 else 42 os<<c.real<<c.imag<<"i"; 43 return os; 44 } 45 };
任务6、

1【Account::show()函数声明为虚函数,这样就发挥了函数的多态】
2【又添加了deposit和withdraw()\settle(),使得Account 成为虚基类,让他的子类完成他的具体实现】

浙公网安备 33010602011771号