博客 / 詳情

返回

實驗5

實驗任務1:

代碼:

publisher.cpp

 1 #include <iostream>
 2 #include <string>
 3 #include "publisher.hpp"
 4 
 5 Publisher::Publisher(const std::string &name_): name {name_} {
 6 }
 7 
 8 
 9 Book::Book(const std::string &name_ , const std::string &author_ ): Publisher{name_}, author{author_} {
10 }
11 
12 void Book::publish() const {
13     std::cout << "Publishing book《" << name << "》 by " << author << '\n';
14 }
15 
16 void Book::use() const {
17     std::cout << "Reading book 《" << name << "》 by " << author << '\n';
18 }
19 
20 
21 Film::Film(const std::string &name_, const std::string &director_):Publisher{name_},director{director_} {
22 }
23 
24 void Film::publish() const {
25     std::cout << "Publishing film <" << name << "> directed by " << director << '\n';
26 }
27 
28 void Film::use() const {
29     std::cout << "Watching film <" << name << "> directed by " << director << '\n';
30 }
31 
32 
33 Music::Music(const std::string &name_, const std::string &artist_): Publisher{name_}, artist{artist_} {
34 }
35 
36 void Music::publish() const {
37     std::cout << "Publishing music <" << name << "> by " << artist << '\n';
38 }
39 
40 void Music::use() const {
41     std::cout << "Listening to music <" << name << "> by " << artist << '\n';
42 }

publisher.hpp

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 class Publisher {
 6 public:
 7     Publisher(const std::string &name_ = "");
 8     virtual ~Publisher() = default;
 9 
10 public:
11     virtual void publish() const = 0;                 // 純虛函數,作為接口繼承
12     virtual void use() const = 0;                     // 純虛函數,作為接口繼承
13 
14 protected:
15     std::string name;    // 發行/出版物名稱
16 };
17 
18 // 圖書類: Book
19 class Book: public Publisher {
20 public:
21     Book(const std::string &name_ = "", const std::string &author_ = "");  // 構造函數
22 
23 public:
24     void publish() const override;        // 接口
25     void use() const override;            // 接口
26 
27 private:
28     std::string author;          // 作者
29 };
30 
31 // 電影類: Film
32 class Film: public Publisher {
33 public:
34     Film(const std::string &name_ = "", const std::string &director_ = "");   // 構造函數
35 
36 public:
37     void publish() const override;    // 接口
38     void use() const override;        // 接口            
39 
40 private:
41     std::string director;        // 導演
42 };
43 
44 
45 // 音樂類:Music
46 class Music: public Publisher {
47 public:
48     Music(const std::string &name_ = "", const std::string &artist_ = "");
49 
50 public:
51     void publish() const override;        // 接口
52     void use() const override;            // 接口
53 
54 private:
55     std::string artist;      // 音樂藝術家名稱
56 };

task1.cpp

 1 #include <memory>
 2 #include <iostream>
 3 #include <vector>
 4 #include "publisher.hpp"
 5 
 6 void test1() {
 7    std::vector<Publisher *> v;
 8 
 9    v.push_back(new Book("Harry Potter", "J.K. Rowling"));
10    v.push_back(new Film("The Godfather", "Francis Ford Coppola"));
11    v.push_back(new Music("Blowing in the wind", "Bob Dylan"));
12 
13    for(Publisher *ptr: v) {
14         ptr->publish();
15         ptr->use();
16         std::cout << '\n';
17         delete ptr;
18    }
19 }
20 
21 void test2() {
22     std::vector<std::unique_ptr<Publisher>> v;
23 
24     v.push_back(std::make_unique<Book>("Harry Potter", "J.K. Rowling"));
25     v.push_back(std::make_unique<Film>("The Godfather", "Francis Ford Coppola"));
26     v.push_back(std::make_unique<Music>("Blowing in the wind", "Bob Dylan"));
27 
28     for(const auto &ptr: v) {
29         ptr->publish();
30         ptr->use();
31         std::cout << '\n';
32     }
33 }
34 
35 void test3() {
36     Book book("A Philosophy of Software Design", "John Ousterhout");
37     book.publish();
38     book.use();
39 }
40 
41 int main() {
42     std::cout << "運行時多態:純虛函數、抽象類\n";
43 
44     std::cout << "\n測試1: 使用原始指針\n";
45     test1();
46 
47     std::cout << "\n測試2: 使用智能指針\n";
48     test2();
49 
50     std::cout << "\n測試3: 直接使用類\n";
51     test3();
52 }

運行測試截圖:

image

回答問題:

問題1:

(1)Publisher類中包含純虛函數。具體依據:virtual void publish() const = 0;和virtual void use() const = 0;

(2)不能編譯通過。因為抽象類不能實例化對象。

問題2:

(1)void publish() const override;

void use() const override;

(2)函數簽名與基類不匹配,無法重寫

問題3:

(1)ptr的聲明類型是Publisher*

(2)Book, Film, Music

(3)原因:實現多態析構,確保刪除派生類對象時,先調用派生類析構函數,再調用基類析構函數,避免內存泄漏;若刪除virtual,派生類的析構函數不被調用,內存泄漏。

 

實驗任務2:

代碼:

book.hpp

 1 #pragma once
 2 #include <string>
 3 
 4 // 圖書描述信息類Book: 聲明
 5 class Book {
 6 public:
 7     Book(const std::string &name_, 
 8          const std::string &author_, 
 9          const std::string &translator_, 
10          const std::string &isbn_, 
11          double price_);
12 
13     friend std::ostream& operator<<(std::ostream &out, const Book &book);
14 
15 private:
16     std::string name;        // 書名
17     std::string author;      // 作者
18     std::string translator;  // 譯者
19     std::string isbn;        // isbn號
20     double price;        // 定價
21 };

book.cpp

 1 #include <iomanip>
 2 #include <iostream>
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 
 7 // 圖書描述信息類Book: 實現
 8 Book::Book(const std::string &name_, 
 9           const std::string &author_, 
10           const std::string &translator_, 
11           const std::string &isbn_, 
12           double price_):name{name_}, author{author_}, translator{translator_}, isbn{isbn_}, price{price_} {
13 }
14 
15 // 運算符<<重載實現
16 std::ostream& operator<<(std::ostream &out, const Book &book) {
17     using std::left;
18     using std::setw;
19     
20     out << left;
21     out << setw(15) << "書名:" << book.name << '\n'
22         << setw(15) << "作者:" << book.author << '\n'
23         << setw(15) << "譯者:" << book.translator << '\n'
24         << setw(15) << "ISBN:" << book.isbn << '\n'
25         << setw(15) << "定價:" << book.price;
26 
27     return out;
28 }

booksale.hpp

 1 #pragma once
 2 
 3 #include <string>
 4 #include "book.hpp"
 5 
 6 // 圖書銷售記錄類BookSales:聲明
 7 class BookSale {
 8 public:
 9     BookSale(const Book &rb_, double sales_price_, int sales_amount_);
10     int get_amount() const;   // 返回銷售數量
11     double get_revenue() const;   // 返回營收
12     
13     friend std::ostream& operator<<(std::ostream &out, const BookSale &item);
14 
15 private:
16     Book rb;         
17     double sales_price;      // 售價
18     int sales_amount;       // 銷售數量
19 };

booksale.cpp

 1 #include <iomanip>
 2 #include <iostream>
 3 #include <string>
 4 #include "booksale.hpp"
 5 
 6 // 圖書銷售記錄類BookSales:實現
 7 BookSale::BookSale(const Book &rb_, 
 8                    double sales_price_, 
 9                    int sales_amount_): rb{rb_}, sales_price{sales_price_}, sales_amount{sales_amount_} {
10 }
11 
12 int BookSale::get_amount() const {
13     return sales_amount;
14 }
15 
16 double BookSale::get_revenue() const {
17     return sales_amount * sales_price;
18 }
19 
20 // 運算符<<重載實現
21 std::ostream& operator<<(std::ostream &out, const BookSale &item) {
22     using std::left;
23     using std::setw;
24     
25     out << left;
26     out << item.rb << '\n'
27         << setw(15) << "售價:" << item.sales_price << '\n'
28         << setw(15) << "銷售數量:" << item.sales_amount << '\n'
29         << setw(15) << "營收:" << item.get_revenue();
30 
31     return out;
32 }

task2.cpp

 1 #include <algorithm>
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include "booksale.hpp"
 7 
 8 // 按圖書銷售數量比較
 9 bool compare_by_amount(const BookSale &x1, const BookSale &x2) {
10     return x1.get_amount() > x2.get_amount();
11 }
12 
13 void test() {
14     using std::cin;
15     using std::cout;
16     using std::getline;
17     using std::sort;
18     using std::string;
19     using std::vector;
20     using std::ws;
21 
22     vector<BookSale> sales_records;         // 圖書銷售記錄表
23 
24     int books_number;
25     cout << "錄入圖書數量: ";
26     cin >> books_number;
27 
28     cout << "錄入圖書銷售記錄\n";
29     for(int i = 0; i < books_number; ++i) {
30         string name, author, translator, isbn;
31         double price;
32         cout << string(20, '-') << "" << i+1 << "本圖書信息錄入" << string(20, '-') << '\n';
33         cout << "錄入書名: "; getline(cin>>ws, name);
34         cout << "錄入作者: "; getline(cin>>ws, author);
35         cout << "錄入譯者: "; getline(cin>>ws, translator);
36         cout << "錄入isbn: "; getline(cin>>ws, isbn);
37         cout << "錄入定價: "; cin >> price;
38 
39         Book book(name, author, translator, isbn, price);
40 
41         double sales_price;
42         int sales_amount;
43 
44         cout << "錄入售價: "; cin >> sales_price;
45         cout << "錄入銷售數量: "; cin >> sales_amount;
46 
47         BookSale record(book, sales_price, sales_amount);
48         sales_records.push_back(record);
49     }
50 
51     // 按銷售冊數排序
52     sort(sales_records.begin(), sales_records.end(), compare_by_amount);
53 
54     // 按銷售冊數降序輸出圖書銷售信息
55     cout << string(20, '=') <<  "圖書銷售統計" << string(20, '=') << '\n';
56     for(auto &record: sales_records) {
57         cout << record << '\n';
58         cout << string(40, '-') << '\n';
59     }
60 }
61 
62 int main() {
63     test();
64 }

運行測試截圖:

image

 回答問題:

問題1:

(1)兩處。Book類型和BookSale類型

(2)book.cpp中:std::ostream& operator<<(std::ostream &out, const Book &book);

booksale.cpp中:std::ostream& operator<<(std::ostream &out, const BookSale &item);

task2.cpp中:cout << t <<endl;

問題2:

(1)使用 std::sort 函數,配合自定義比較函數 compare_by_amount

 

實驗任務4:

pet.hpp

 1 #pragma once
 2 #include <string>
 3 
 4 class MachinePet {
 5 public:
 6     MachinePet(const std::string& nickname_) : nickname(nickname_) {}
 7     virtual ~MachinePet() = default;
 8 
 9     std::string get_nickname() const {
10         return nickname;
11     }
12 
13     virtual std::string talk() const = 0;
14 
15 protected:
16     std::string nickname;
17 };
18 
19 class PetCat : public MachinePet {
20 public:
21     PetCat(const std::string& nickname_) : MachinePet(nickname_) {}
22 
23     std::string talk() const override {
24         return "miao wu~";
25     }
26 };
27 
28 class PetDog : public MachinePet {
29 public:
30     PetDog(const std::string& nickname_) : MachinePet(nickname_) {}
31 
32     std::string talk() const override {
33         return "wang wang~";
34     }
35 };

task4.cpp

 1 #include <iostream>
 2 #include <memory>
 3 #include <vector>
 4 #include "pet.hpp"
 5 
 6 void test1() {
 7     std::vector<MachinePet *> pets;
 8 
 9     pets.push_back(new PetCat("miku"));
10     pets.push_back(new PetDog("da huang"));
11 
12     for(MachinePet *ptr: pets) {
13         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
14         delete ptr;  // 須手動釋放資源
15     }   
16 }
17 
18 void test2() {
19     std::vector<std::unique_ptr<MachinePet>> pets;
20 
21     pets.push_back(std::make_unique<PetCat>("miku"));
22     pets.push_back(std::make_unique<PetDog>("da huang"));
23 
24     for(auto const &ptr: pets)
25         std::cout << ptr->get_nickname() << " says " << ptr->talk() << '\n';
26 }
27 
28 void test3() {
29     // MachinePet pet("little cutie");   // 編譯報錯:無法定義抽象類對象
30 
31     const PetCat cat("miku");
32     std::cout << cat.get_nickname() << " says " << cat.talk() << '\n';
33 
34     const PetDog dog("da huang");
35     std::cout << dog.get_nickname() << " says " << dog.talk() << '\n';
36 }
37 
38 int main() {
39     std::cout << "測試1: 使用原始指針\n";
40     test1();
41 
42     std::cout << "\n測試2: 使用智能指針\n";
43     test2();
44 
45     std::cout << "\n測試3: 直接使用類\n";
46     test3();
47 }

運行測試截圖:

43c8811905a47aca7d3b65c71f75bae7

 

實驗任務5:

Complex.hpp

 1 #pragma once
 2 #include <iostream>
 3 
 4 template<typename T>
 5 class Complex {
 6 private:
 7     T real;
 8     T imag;
 9     
10 public:
11     Complex() : real(0), imag(0) {}
12     Complex(T real_, T imag_) : real(real_), imag(imag_) {}
13     Complex(const Complex &other) : real(other.real), imag(other.imag) {}
14 
15     T get_real() const { return real; }
16     T get_imag() const { return imag; }
17 
18     Complex &operator+=(const Complex &other) {
19         real += other.real;
20         imag += other.imag;
21         return *this;
22     }
23 
24     friend Complex operator+(const Complex &c1, const Complex &c2) {
25         Complex temp = c1;
26         temp += c2;
27         return temp;
28     }
29 
30     friend bool operator==(const Complex &c1, const Complex &c2) {
31         return c1.real == c2.real && c1.imag == c2.imag;
32     }
33 
34     friend std::ostream &operator<<(std::ostream &out, const Complex &c) {
35         out << c.real;
36         if (c.imag >= 0) {
37             out << "+" << c.imag << "i";
38         } else {
39             out << c.imag << "i";
40         }
41         return out;
42     }
43 
44     friend std::istream &operator>>(std::istream &in, Complex &c) {
45         in >> c.real >> c.imag;
46         return in;
47     }
48 
49 };

task5.cpp

 1 #include <iostream>
 2 #include "Complex.hpp"
 3 
 4 void test1() {
 5     using std::cout;
 6     using std::boolalpha;
 7     
 8     Complex<int> c1(2, -5), c2(c1);
 9 
10     cout << "c1 = " << c1 << '\n';
11     cout << "c2 = " << c2 << '\n';
12     cout << "c1 + c2 = " << c1 + c2 << '\n';
13     
14     c1 += c2;
15     cout << "c1 = " << c1 << '\n';
16     cout << boolalpha << (c1 == c2) << '\n';
17 }
18 
19 void test2() {
20     using std::cin;
21     using std::cout;
22 
23     Complex<double> c1, c2;
24     cout << "Enter c1 and c2: ";
25     cin >> c1 >> c2;
26     cout << "c1 = " << c1 << '\n';
27     cout << "c2 = " << c2 << '\n';
28 
29     const Complex<double> c3(c1);
30     cout << "c3.real = " << c3.get_real() << '\n';
31     cout << "c3.imag = " << c3.get_imag() << '\n';
32 }
33 
34 int main() {
35     std::cout << "自定義類模板Complex測試1: \n";
36     test1();
37 
38     std::cout << "\n自定義類模板Complex測試2: \n";
39     test2();
40 }

運行測試截圖:

image

 

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.