1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 6 using std::cout; 7 using std::endl; 8 using std::string; 9 10 // 发行/出版物类:Publisher (抽象类) 11 class Publisher { 12 public: 13 Publisher(const string &s = ""); // 构造函数 14 15 public: 16 virtual void publish() const = 0; // 纯虚函数,作为接口继承 17 virtual void use() const = 0; // 纯虚函数,作为接口继承 18 19 protected: 20 string name; // 发行/出版物名称 21 }; 22 23 Publisher::Publisher(const string &s): name {s} { 24 } 25 26 27 // 图书类: Book 28 class Book: public Publisher { 29 public: 30 Book(const string &s = "", const string &a = ""); // 构造函数 31 32 public: 33 void publish() const override; // 接口 34 void use() const override; // 接口 35 36 private: 37 string author; // 作者 38 }; 39 40 Book::Book(const string &s, const string &a): Publisher{s}, author{a} { 41 } 42 43 void Book::publish() const { 44 cout << "Publishing book: 《" << name << "》 by " << author << endl; 45 } 46 47 void Book::use() const { 48 cout << "Reading book: " << name << " by " << author << endl; 49 } 50 51 52 // 电影类: Film 53 class Film: public Publisher { 54 public: 55 Film(const string &s = "", const string &d = ""); // 构造函数 56 57 public: 58 void publish() const override; // 接口 59 void use() const override; // 接口 60 61 private: 62 string director; // 导演 63 }; 64 65 Film::Film(const string &s, const string &d): Publisher{s}, director{d} { 66 } 67 68 void Film::publish() const { 69 cout << "Publishing film: <" << name << "> directed by " << director << endl; 70 } 71 72 void Film::use() const { 73 cout << "Watching film: " << name << " directed by " << director << endl; 74 } 75 76 77 // 音乐类:Music 78 class Music: public Publisher { 79 public: 80 Music(const string &s = "", const string &a = ""); 81 82 public: 83 void publish() const override; // 接口 84 void use() const override; // 接口 85 86 private: 87 string artist; // 音乐艺术家名称 88 }; 89 90 91 92 93 #include "publisher.hpp" 94 #include <vector> 95 #include <typeinfo> 96 97 using std::vector; 98 99 void test() { 100 vector<Publisher *> v; 101 102 v.push_back(new Book("Harry Potter", "J.K. Rowling")); 103 v.push_back(new Film("The Godfather", "Francis Ford Coppola")); 104 v.push_back(new Music("Blowing in the wind", "Bob Dylan")); 105 106 for(auto &ptr: v) { 107 cout << "pointer type: " << typeid(ptr).name() << endl; // 输出指针类型 108 cout << "RTTI type: " << typeid(*ptr).name() << endl; // 输出指针指向的对象类型 109 ptr->publish(); 110 ptr->use(); 111 cout << endl; 112 } 113 } 114 115 int main() { 116 test(); 117 }
1 #pragma once 2 3 #include <string> 4 #include <iostream> 5 #include <iomanip> 6 7 using std::string; 8 using std::ostream; 9 using std::endl; 10 using std::setw; 11 using std::left; 12 13 class Book { 14 public: 15 Book(const string &name, const string &author, const string &translator, const string &isbn, float price); 16 17 friend ostream& operator<<(ostream &out, const Book &book); 18 19 private: 20 string name; // 书名 21 string author; // 作者 22 string translator; // 译者 23 string isbn; // isbn号 24 float price; // 定价 25 }; 26 27 // 成员函数实现 28 Book::Book(const string &name, const string &author, const string &translator, const string &isbn, float price) { 29 this->name = name; 30 this->author = author; 31 this->translator = translator; 32 this->isbn = isbn; 33 this->price = price; 34 } 35 36 // 友元实现 37 ostream& operator<<(ostream &out, const Book &book) { 38 out << left; 39 out << setw(15) << "书名:" << book.name << endl 40 << setw(15) << "作者:" << book.author << endl 41 << setw(15) << "译者:" << book.translator << endl 42 << setw(15) << "ISBN:" << book.isbn << endl 43 << setw(15) << "定价:" << book.price; 44 45 return out; 46 } 47 48 49 50 51 #pragma once 52 53 #include "book.hpp" 54 #include <iostream> 55 #include <string> 56 #include <iomanip> 57 58 using std::string; 59 using std::cout; 60 using std::endl; 61 using std::setw; 62 63 class BookSale { 64 public: 65 BookSale(const Book &b, float price, int amount); 66 int get_amount() const; 67 68 friend ostream& operator<<(ostream &out, const BookSale &item); 69 70 private: 71 Book rb; 72 float sales_price; // 售价 73 int sales_amount; // 销售数量 74 float revenue; // 营收 75 }; 76 77 // 成员函数实现 78 BookSale::BookSale(const Book &b, float price, int amount): rb{b}, sales_price(price), sales_amount{amount} { 79 revenue = sales_amount * sales_price; 80 } 81 82 int BookSale::get_amount() const { 83 return sales_amount; 84 } 85 86 // 友元函数实现 87 ostream& operator<<(ostream &out, const BookSale &item) { 88 out << left; 89 out << item.rb << endl 90 << setw(15) << "售价:" << item.sales_price << endl 91 << setw(15) << "销售数量:" << item.sales_amount << endl 92 << setw(15) << "营收:" << item.revenue; 93 94 return out; 95 } 96 97 98 99 100 #include "booksale.hpp" 101 #include <iostream> 102 #include <string> 103 #include <vector> 104 #include <algorithm> 105 106 // 按图书销售数额比较 107 bool compare_by_amount(const BookSale &x1, const BookSale &x2) { 108 return x1.get_amount() > x2.get_amount(); 109 } 110 111 void test() { 112 using namespace std; 113 114 vector<BookSale> sales_lst; // 存放图书销售记录 115 116 int books_number; 117 cout << "录入图书数量: "; 118 cin >> books_number; 119 120 cout << "录入图书销售记录" << endl; 121 for(int i = 0; i < books_number; ++i) { 122 string name, author, translator, isbn; 123 float price; 124 cout << string(20, '-') << "第" << i+1 << "本图书信息录入" << string(20, '-') << endl; 125 cout << "录入书名: "; cin >> name; 126 cout << "录入作者: "; cin >> author; 127 cout << "录入译者: "; cin >> translator; 128 cout << "录入isbn: "; cin >> isbn; 129 cout << "录入定价: "; cin >> price; 130 131 Book book(name, author, translator, isbn, price); 132 133 float sales_price; 134 int sales_amount; 135 136 cout << "录入售价: "; cin >> sales_price; 137 cout << "录入销售数量: "; cin >> sales_amount; 138 139 BookSale record(book, sales_price, sales_amount); 140 sales_lst.push_back(record); 141 } 142 143 // 按销售册数排序 144 sort(sales_lst.begin(), sales_lst.end(), compare_by_amount); 145 146 // 按销售册数降序输出图书销售信息 147 cout << string(20, '=') << "图书销售统计" << string(20, '=') << endl; 148 for(auto &t: sales_lst) { 149 cout << t << endl; 150 cout << string(40, '-') << endl; 151 } 152 } 153 154 int main() { 155 test(); 156 }
1 #ifndef PETS_HPP 2 #define PETS_HPP 3 4 #include <string> 5 #include <iostream> 6 7 class MachinePets { 8 protected: 9 std::string nickname; 10 public: 11 12 explicit MachinePets(const std::string &nickname) : nickname(nickname) {} 13 14 virtual ~MachinePets() {} 15 16 std::string get_nickname() const { 17 return nickname; 18 } 19 20 virtual std::string talk() const = 0; 21 }; 22 23 class PetCats : public MachinePets { 24 public: 25 26 explicit PetCats(const std::string &nickname) : MachinePets(nickname) {} 27 28 std::string talk() const override { 29 return "miao~"; 30 } 31 }; 32 33 class PetDogs : public MachinePets { 34 public: 35 36 explicit PetDogs(const std::string &nickname) : MachinePets(nickname) {} 37 38 std::string talk() const override { 39 return "wang wang~"; 40 } 41 }; 42 43 #endif 44 45 46 #include <iostream> 47 #include <vector> 48 #include "pets.hpp" 49 50 void test() { 51 using namespace std; 52 53 vector<MachinePets *> pets; 54 55 pets.push_back(new PetCats("miku")); 56 pets.push_back(new PetDogs("da huang")); 57 58 for(auto &ptr: pets) 59 cout <<ptr->get_nickname() << " says " << ptr->talk() << endl; 60 } 61 62 int main() { 63 test(); 64 }
1 #ifndef FILM_HPP 2 #define FILM_HPP 3 4 #include <string> 5 #include <iostream> 6 7 // Film 类定义 8 class Film { 9 private: 10 std::string title; // 片名 11 std::string director; // 导演 12 std::string country; // 制片国家/地区 13 int year; // 上映年份 14 15 public: 16 // 默认构造函数 17 Film() : title(""), director(""), country(""), year(0) {} 18 19 // 带参数的构造函数 20 Film(const std::string &title, const std::string &director, const std::string &country, int year) 21 : title(title), director(director), country(country), year(year) {} 22 23 // 输入流运算符重载,用于读取电影信息 24 friend std::istream &operator>>(std::istream &is, Film &film) { 25 std::cout << "输入片名: "; 26 std::getline(is, film.title); 27 std::cout << "输入导演: "; 28 std::getline(is, film.director); 29 std::cout << "输入制片国家/地区: "; 30 std::getline(is, film.country); 31 std::cout << "输入上映年份: "; 32 is >> film.year; 33 is.ignore(); // 清除缓冲区中的换行符 34 return is; 35 } 36 37 // 输出流运算符重载,用于输出电影信息 38 friend std::ostream &operator<<(std::ostream &os, const Film &film) { 39 os << film.title << "\t" << film.director << "\t" << film.country << "\t" << film.year; 40 return os; 41 } 42 43 // 按年份排序的比较函数 44 static bool compare_by_year(const Film &a, const Film &b) { 45 return a.year < b.year; 46 } 47 }; 48 49 #endif // FILM_HPP 50 51 52 53 54 #include "film.hpp" 55 #include <iostream> 56 #include <string> 57 #include <vector> 58 #include <algorithm> 59 60 void test() { 61 using namespace std; 62 63 int n; 64 cout << "输入电影数目: "; 65 cin >> n; 66 67 cout << "录入" << n << "部影片信息" << endl; 68 vector<Film> film_lst; 69 for(int i = 0; i < n; ++i) { 70 Film f; 71 cout << string(20, '-') << "第" << i+1 << "部影片录入" << string(20, '-') << endl; 72 cin >> f; 73 film_lst.push_back(f); 74 } 75 76 // 按发行年份升序排序 77 sort(film_lst.begin(), film_lst.end(), compare_by_year); 78 79 cout << string(20, '=') + "电影信息(按发行年份)" + string(20, '=')<< endl; 80 for(auto &f: film_lst) 81 cout << f << endl; 82 } 83 84 int main() { 85 test(); 86 }
1 #include "Complex.hpp" 2 #include <iostream> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::boolalpha; 8 9 void test1() { 10 Complex<int> c1(2, -5), c2(c1); 11 12 cout << "c1 = " << c1 << endl; 13 cout << "c2 = " << c2 << endl; 14 cout << "c1 + c2 = " << c1 + c2 << endl; 15 16 c1 += c2; 17 cout << "c1 = " << c1 << endl; 18 cout << boolalpha << (c1 == c2) << endl; 19 } 20 21 void test2() { 22 Complex<double> c1, c2; 23 cout << "Enter c1 and c2: "; 24 cin >> c1 >> c2; 25 cout << "c1 = " << c1 << endl; 26 cout << "c2 = " << c2 << endl; 27 28 cout << "c1.real = " << c1.get_real() << endl; 29 cout << "c1.imag = " << c1.get_imag() << endl; 30 } 31 32 int main() { 33 cout << "自定义类模板Complex测试1: " << endl; 34 test1(); 35 36 cout << endl; 37 38 cout << "自定义类模板Complex测试2: " << endl; 39 test2(); 40 } 41 42 43 44 45 #ifndef COMPLEX_HPP 46 #define COMPLEX_HPP 47 48 #include <iostream> 49 50 // 模板类 Complex 定义 51 template <typename T> 52 class Complex { 53 private: 54 T real; // 实部 55 T imag; // 虚部 56 57 public: 58 // 默认构造函数 59 Complex() : real(0), imag(0) {} 60 61 // 带参数构造函数 62 Complex(T real, T imag) : real(real), imag(imag) {} 63 64 // 拷贝构造函数 65 Complex(const Complex &other) : real(other.real), imag(other.imag) {} 66 67 // 获取实部 68 T get_real() const { 69 return real; 70 } 71 72 // 获取虚部 73 T get_imag() const { 74 return imag; 75 } 76 77 // 运算符重载:加法 78 Complex operator+(const Complex &other) const { 79 return Complex(real + other.real, imag + other.imag); 80 } 81 82 // 运算符重载:+= 83 Complex &operator+=(const Complex &other) { 84 real += other.real; 85 imag += other.imag; 86 return *this; 87 } 88 89 // 运算符重载:相等比较 90 bool operator==(const Complex &other) const { 91 return real == other.real && imag == other.imag; 92 } 93 94 // 运算符重载:输入流 95 friend std::istream &operator>>(std::istream &is, Complex &c) { 96 std::cout << "Real part: "; 97 is >> c.real; 98 std::cout << "Imaginary part: "; 99 is >> c.imag; 100 return is; 101 } 102 103 // 运算符重载:输出流 104 friend std::ostream &operator<<(std::ostream &os, const Complex &c) { 105 os << c.real << " + " << c.imag << "i"; 106 return os; 107 } 108 }; 109 110 #endif // COMPLEX_HPP
1 date.h 2 #pragma once 3 class Date { 4 private: 5 int year; 6 int month; 7 int day; 8 int totalDays; 9 public: 10 Date(int year, int month, int day); 11 int getYear()const { return year; } 12 int getMonth()const { return month; } 13 int getDay()const { return day; } 14 int getMaxDay()const; 15 bool isLeapYear()const { 16 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 17 } 18 void show() const; 19 int operator-(const Date& date)const { 20 return totalDays - date.totalDays; 21 } 22 }; 23 24 date.cpp 25 #include"date.h" 26 #include<iostream> 27 #include<cstdlib> 28 using namespace std; 29 namespace { 30 const int DAYS_BEFIRE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304 ,334,365 }; 31 } 32 Date::Date(int year, int month, int day) :year(year), month(month), day(day) { 33 if (day <= 0 || day > getMaxDay()) { 34 cout << "Invalid date: "; 35 show(); 36 cout << endl; 37 exit(1); 38 } 39 int years = year - 1; 40 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFIRE_MONTH[month - 1] + day; 41 if (isLeapYear() && month > 2) totalDays++; 42 } 43 int Date::getMaxDay()const { 44 if (isLeapYear() && month == 2) 45 return 29; 46 else return DAYS_BEFIRE_MONTH[month] - DAYS_BEFIRE_MONTH[month - 1]; 47 } 48 void Date::show()const { 49 cout << getYear() << "-" << getMonth() << "-" << getDay(); 50 } 51 52 accumulator.h 53 #pragma once 54 #include "date.h" 55 class Accumulator { 56 private: 57 Date lastDate; 58 double value; 59 double sum; 60 public: 61 Accumulator(const Date& date, double value) :lastDate(date), value(value), sum{ 0 } {} 62 double getSum(const Date& date) const { 63 return sum + value * (date-lastDate); 64 } 65 void change(const Date& date, double value) { 66 sum = getSum(date); 67 lastDate = date; 68 this->value = value; 69 } 70 void reset(const Date& date, double value) { 71 lastDate = date; 72 this->value; 73 sum = 0; 74 } 75 }; 76 77 account.h 78 #pragma once 79 #include"date.h" 80 #include"accumulator.h" 81 #include<string> 82 using namespace std; 83 class Account { 84 private: 85 string id; 86 double balance; 87 static double total; 88 protected: 89 Account(const Date& date, const string& id); 90 void record(const Date& date, double amount, const string& desc); 91 void error(const string& msg) const; 92 public:const string& getId() { return id; } 93 double getBalance()const { return balance; } 94 static double getTotal() { return total; } 95 virtual void deposit(const Date& date, double amount, const string& desc) = 0; 96 virtual void withdraw(const Date& date, double amount, const string& desc) = 0; 97 virtual void settle(const Date& date) = 0; 98 virtual void show()const; 99 }; 100 class SavingsAccount :public Account { 101 private: 102 Accumulator acc; 103 double rate; 104 public: 105 SavingsAccount(const Date& date, const string& id, double rate); 106 double getRate() const { return rate; } 107 void deposit(const Date& date, double amount, const string& desc); 108 void withdraw(const Date& date, double amount, const string& desc); 109 void settle(const Date& date); 110 }; 111 class CreditAccount :public Account { 112 private: 113 Accumulator acc; 114 double credit; 115 double rate; 116 double fee; 117 double getDebt()const { 118 double balance = getBalance(); 119 return(balance < 0 ? balance : 0); 120 } 121 public:CreditAccount(const Date& date, const string& id, double credit, double rate, double fee); 122 double getCredit()const { return credit; } 123 double getRate()const { return rate; } 124 double getFee() const { return fee; } 125 double getAvailableCredit()const { 126 if (getBalance() < 0)return credit + getBalance(); 127 else return credit; 128 } 129 void deposit(const Date& date, double amount, const string& desc); 130 void withdraw(const Date& date, double amount, const string& desc); 131 void settle(const Date& date); 132 void show()const; 133 }; 134 135 account.cpp 136 #include "account.h" 137 #include <cmath> 138 #include<iostream> 139 using namespace std; 140 double Account::total = 0; 141 Account::Account(const Date& date, const string& id) :id(id), balance(0) { 142 date.show(); 143 cout << "\t#" << id << "created" << endl; 144 } 145 void Account::record(const Date& date, double amount, const string& desc) { 146 amount = floor(amount * 100 + 0.5) / 100; 147 balance += amount; 148 total += amount; 149 date.show(); 150 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 151 } 152 void Account::show()const { cout << id << "\tBalance:" << balance; } 153 void Account::error(const string& msg)const { 154 cout << "Error(#" << id << "):" << msg << endl; 155 } 156 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {} 157 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 158 record(date, amount, desc); 159 acc.change(date, getBalance()); 160 } 161 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 162 if (amount > getBalance()) { 163 error("not enough money"); 164 } 165 else { 166 record(date, -amount, desc); 167 acc.change(date, getBalance()); 168 } 169 } 170 void SavingsAccount::settle(const Date& date) { 171 if (date.getMonth() == 1) { 172 double interest = acc.getSum(date) * rate / (date - Date(date.getYear() - 1, 1, 1)); 173 if (interest != 0) record(date, interest, "interest"); 174 acc.reset(date, getBalance()); 175 } 176 } 177 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) :Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {} 178 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 179 record(date, amount, desc); 180 acc.change(date, getDebt()); 181 } 182 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { 183 if (amount - getBalance() > credit) { 184 error("not enouogh credit"); 185 } 186 else { 187 record(date, -amount, desc); 188 acc.change(date, getDebt()); 189 } 190 } 191 void CreditAccount::settle(const Date& date) { 192 double interest = acc.getSum(date) * rate; 193 if (interest != 0) record(date, interest, "interest"); 194 if (date.getMonth() == 1)record(date, -fee, "annual fee"); 195 acc.reset(date, getDebt()); 196 } 197 void CreditAccount::show()const { 198 Account::show(); 199 cout << "\tAvailable credit:" << getAvailableCredit(); 200 } 201 202 cpp 203 #include"account.h" 204 #include<iostream> 205 using namespace std; 206 int main() { 207 Date date(2008, 11, 1); 208 SavingsAccount sa1(date, "S3755217", 0.015); 209 SavingsAccount sa2(date, "02342342", 0.015); 210 CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); 211 Account* accounts[] = { &sa1,&sa2,&ca }; 212 const int n = sizeof(accounts) / sizeof(Account*); 213 cout << "(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl; 214 char cmd; 215 do { 216 date.show(); 217 cout << "\tTotal:" << Account::getTotal() << "\tcommand>"; 218 int index, day; 219 double amount; 220 string desc; 221 cin >> cmd; 222 switch (cmd) { 223 case 'd': 224 cin >> index >> amount; 225 getline(cin, desc); 226 accounts[index]->deposit(date, amount, desc); 227 break; 228 229 case 'w': 230 cin >> index >> amount; 231 getline(cin, desc); 232 accounts[index]->withdraw(date, amount, desc); 233 break; 234 case 's': 235 for (int i = 0; i < n; i++) { 236 cout << "[" << i << "]"; 237 accounts[i]->show(); 238 cout << endl; 239 } 240 break; 241 242 case 'c': 243 cin >> day; 244 if (day < date.getDay()) { 245 cout << "You cannot specify a previous day"; 246 } 247 else if (day > date.getMaxDay()) 248 cout << "Invalid day"; 249 else date = Date(date.getYear(), date.getMonth(), day); 250 break; 251 case 'n': 252 if (date.getMonth() == 12) 253 date = Date(date.getYear() + 1, 1, 1); 254 else date = Date(date.getYear(), date.getMonth() + 1, 1); 255 for (int i = 0; i < n; i++) { 256 accounts[i]->settle(date); 257 } 258 break; 259 } 260 } while (cmd != 'e'); 261 return 0; 262 }