任務1:
原始碼:
1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 6 using std::string; 7 using std::cout; 8 9 // 按鈕類 10 class Button { 11 public: 12 Button(const string &text); 13 string get_label() const; 14 void click(); 15 16 private: 17 string label; 18 }; 19 20 Button::Button(const string &text): label{text} { 21 } 22 23 inline string Button::get_label() const { 24 return label; 25 } 26 27 void Button::click() { 28 cout << "Button '" << label << "' clicked\n"; 29 }
1 #pragma once 2 #include "button.hpp" 3 #include <vector> 4 #include <iostream> 5 6 using std::vector; 7 using std::cout; 8 using std::endl; 9 10 // 視窗類 11 class Window{ 12 public: 13 Window(const string &win_title); 14 void display() const; 15 void close(); 16 void add_button(const string &label); 17 18 private: 19 string title; 20 vector<Button> buttons; 21 }; 22 23 Window::Window(const string &win_title): title{win_title} { 24 buttons.push_back(Button("close")); 25 } 26 27 inline void Window::display() const { 28 string s(40, '*'); 29 30 cout << s << endl; 31 cout << "window title: " << title << endl; 32 cout << "It has " << buttons.size() << " buttons: " << endl; 33 for(const auto &i: buttons) 34 cout << i.get_label() << " button" << endl; 35 cout << s << endl; 36 } 37 38 void Window::close() { 39 cout << "close window '" << title << "'" << endl; 40 buttons.at(0).click(); 41 } 42 43 void Window::add_button(const string &label) { 44 buttons.push_back(Button(label)); 45 }
1 #include "window.hpp" 2 #include <iostream> 3 4 using std::cout; 5 using std::cin; 6 7 void test() { 8 Window w1("new window"); 9 w1.add_button("maximize"); 10 w1.display(); 11 w1.close(); 12 } 13 14 int main() { 15 cout << "用組合類模擬簡單GUI:\n"; 16 test(); 17 }
結果:
回答:
問題1:這個模擬簡單GUI的示例程式碼中,自定義了幾個類?使用到了標準庫的哪幾個類?,
哪些類和類之間存在組合關係?
兩個類,
vector,
button類是vector中的元素,該vector是window類的成員。
問題2:在自定義類Button和Window中,有些成員函式定義時加了const, 有些設定成了
inline。如果你是類的設計者,目前那些沒有加const或沒有設定成inline的,適合新增const,
適合設定成inline嗎?你的思考依據是?
Button::click和Window::close不適合加inline,在實際專案中該函式執行的內容較複雜,不必新增const,因為沒有資料的傳輸。
Window::add不適合加inline,需要更改物件內容。
問題3:類Window的定義中,有這樣一行程式碼,其功能是?
視窗分隔線。
任務2:
原始碼:
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 void output1(const vector<int> &v) { 7 for(auto &i: v) 8 cout << i << ", "; 9 cout << "\b\b \n"; 10 } 11 12 void output2(const vector<vector<int>> v) { 13 for(auto &i: v) { 14 for(auto &j: i) 15 cout << j << ", "; 16 cout << "\b\b \n"; 17 } 18 } 19 20 void test1() { 21 vector<int> v1(5, 42); 22 const vector<int> v2(v1); 23 24 v1.at(0) = -999; 25 cout << "v1: "; output1(v1); 26 cout << "v2: "; output1(v2); 27 cout << "v1.at(0) = " << v1.at(0) << endl; 28 cout << "v2.at(0) = " << v2.at(0) << endl; 29 } 30 31 void test2() { 32 vector<vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}}; 33 const vector<vector<int>> v2(v1); 34 35 v1.at(0).push_back(-999); 36 cout << "v1: \n"; output2(v1); 37 cout << "v2: \n"; output2(v2); 38 39 vector<int> t1 = v1.at(0); 40 cout << t1.at(t1.size()-1) << endl; 41 42 const vector<int> t2 = v2.at(0); 43 cout << t2.at(t2.size()-1) << endl; 44 } 45 46 int main() { 47 cout << " 1:\n"; 48 test1(); 49 50 cout << "\n 2:\n"; 51 test2(); 52 }
結果:
答:
問題1:測試1模組中,這三行程式碼的功能分別是?
構造大小為5,元素值為42的vector物件。
利用v1複製構造v2。
將v1的第一個值改為-999.
問題2:測試2模組中,這三行程式碼的功能分別是?
構造以vector物件為元素的vector物件。
利用v1複製構造v2。
獲取v1中的第一個vector物件元素,並在該物件末尾增加元素-999。
問題3:測試2模組中,這四行程式碼的功能分別是?
將v1中第一個元素值付給t1的第一個元素。
輸出t1的最後一個元素值。
將v2中第一個元素值付給t2的第一個元素。
輸出t2的最後一個元素值。
問題4:根據執行結果,反向分析、推斷:
① 標準庫模板類vector內部封裝的複製建構函式,其實現機制是深複製還是淺複製?
深複製
② 模板類vector的介面at(), 是否至少需要提供一個const成員函式作為介面?
是
任務3:
原始碼:
1 #pragma once 2 3 #include <iostream> 4 #include <cassert> 5 6 using std::cout; 7 using std::endl; 8 9 // 動態int陣列物件類 10 class vectorInt{ 11 public: 12 vectorInt(int n); 13 vectorInt(int n, int value); 14 vectorInt(const vectorInt &vi); 15 ~vectorInt(); 16 17 int& at(int index); 18 const int& at(int index) const; 19 20 vectorInt& assign(const vectorInt &v); 21 int get_size() const; 22 23 private: 24 int size; 25 int *ptr; // ptr指向包含size個int的陣列 26 }; 27 28 vectorInt::vectorInt(int n): size{n}, ptr{new int[size]} { 29 } 30 31 vectorInt::vectorInt(int n, int value): size{n}, ptr{new int[size]} { 32 for(auto i = 0; i < size; ++i) 33 ptr[i] = value; 34 } 35 36 vectorInt::vectorInt(const vectorInt &vi): size{vi.size}, ptr{new int[size]} { 37 for(auto i = 0; i < size; ++i) 38 ptr[i] = vi.ptr[i]; 39 } 40 41 vectorInt::~vectorInt() { 42 delete [] ptr; 43 } 44 45 const int& vectorInt::at(int index) const { 46 assert(index >= 0 && index < size); 47 48 return ptr[index]; 49 } 50 51 int& vectorInt::at(int index) { 52 assert(index >= 0 && index < size); 53 54 return ptr[index]; 55 } 56 57 vectorInt& vectorInt::assign(const vectorInt &v) { 58 delete[] ptr; // 釋放物件中ptr原來指向的資源 59 60 size = v.size; 61 ptr = new int[size]; 62 63 for(int i = 0; i < size; ++i) 64 ptr[i] = v.ptr[i]; 65 66 return *this; 67 } 68 69 int vectorInt::get_size() const { 70 return size; 71 }
1 #include "vectorInt.hpp" 2 #include <iostream> 3 4 using std::cin; 5 using std::cout; 6 7 void output(const vectorInt &vi) { 8 for(auto i = 0; i < vi.get_size(); ++i) 9 cout << vi.at(i) << ", "; 10 cout << "\b\b \n"; 11 } 12 13 14 void test1() { 15 int n; 16 cout << "Enter n: "; 17 cin >> n; 18 19 vectorInt x1(n); 20 for(auto i = 0; i < n; ++i) 21 x1.at(i) = i*i; 22 cout << "x1: "; output(x1); 23 24 vectorInt x2(n, 42); 25 vectorInt x3(x2); 26 x2.at(0) = -999; 27 cout << "x2: "; output(x2); 28 cout << "x3: "; output(x3); 29 } 30 31 void test2() { 32 const vectorInt x(5, 42); 33 vectorInt y(10, 0); 34 35 cout << "y: "; output(y); 36 y.assign(x); 37 cout << "y: "; output(y); 38 39 cout << "x.at(0) = " << x.at(0) << endl; 40 cout << "y.at(0) = " << y.at(0) << endl; 41 } 42 43 int main() { 44 cout << "測試1: \n"; 45 test1(); 46 47 cout << "\n測試2: \n"; 48 test2(); 49 }
結果:
答:
問題1:vectorInt類中,複製建構函式(line14)的實現,是深複製還是淺複製?
深複製
問題2:vectorInt類中,這兩個at()介面,如果返回值型別改成int而非int&(相應地,實現部
分也同步修改),測試程式碼還能正確執行嗎?
能
如果把line18返回值型別前面的const掉,針對
這個測試程式碼,是否有潛在安全隱患?嘗試分析說明。
有,內部元素值會被修改。
問題3:vectorInt類中,assign()介面,返回值型別可以改成vectorInt嗎?你的結論,及,原
因分析。
不能,增加了複製開銷。
任務4:
原始碼:
1 #pragma once 2 3 #include <iostream> 4 #include <cassert> 5 6 using std::cout; 7 using std::endl; 8 9 // 類Matrix的宣告 10 class Matrix { 11 public: 12 Matrix(int n, int m); // 建構函式,構造一個n*m的矩陣, 初始值為value 13 Matrix(int n); // 建構函式,構造一個n*n的矩陣, 初始值為value 14 Matrix(const Matrix &x); // 複製建構函式, 使用已有的矩陣X構造 15 ~Matrix(); 16 17 void set(const double *pvalue); // 用pvalue指向的連續記憶體塊資料按行為矩陣賦值 18 void clear(); // 把矩陣物件的值置0 19 20 const double& at(int i, int j) const; // 返回矩陣物件索引(i,j)的元素const引用 21 double& at(int i, int j); // 返回矩陣物件索引(i,j)的元素引用 22 23 int get_lines() const; // 返回矩陣物件行數 24 int get_cols() const; // 返回矩陣物件列數 25 26 void display() const; // 按行顯示矩陣物件元素值 27 28 private: 29 int lines; // 矩陣物件內元素行數 30 int cols; // 矩陣物件內元素列數 31 double *ptr; 32 }; 33 34 // 類Matrix的實現:待補足 35 Matrix::Matrix(int n, int m) { 36 lines = n; 37 cols = m; 38 ptr = (double*)malloc(sizeof(double) * n * m); 39 } 40 Matrix::Matrix(int n) { 41 lines = n; 42 cols = n; 43 ptr = (double*)malloc(sizeof(double) * n * n); 44 } 45 Matrix::Matrix(const Matrix& x) { 46 lines = x.get_lines(); 47 cols = x.get_cols(); 48 ptr = (double*)malloc(sizeof(double) * lines * cols); 49 int i, j; 50 int line = x.get_lines(); 51 int col = x.get_cols(); 52 for (i = 0; i < line; i++) { 53 for (j = 0; j < col; j++) { 54 *(ptr + cols * i + j) = *(x.ptr + cols * i + j); 55 } 56 } 57 } 58 Matrix::~Matrix() { 59 60 } 61 int Matrix::get_lines() const { 62 return lines; 63 } 64 int Matrix::get_cols()const { 65 return cols; 66 } 67 void Matrix::set(const double* pvalue) { 68 int i, j; 69 int line = get_lines(); 70 int col = get_cols(); 71 for (i = 0; i < line; i++) { 72 for (j = 0; j < col; j++) { 73 *(ptr + cols * i + j) = *(pvalue + cols * i + j); 74 } 75 } 76 } 77 void Matrix::clear() { 78 int i, j; 79 int line = get_lines(); 80 int col = get_cols(); 81 for (i = 0; i < line; i++) { 82 for (j = 0; j < col; j++) { 83 *(ptr + cols * i + j) = 0; 84 } 85 } 86 } 87 const double& Matrix::at(int i, int j) const { 88 return *(ptr + cols * i + j); 89 } 90 double& Matrix::at(int i, int j) { 91 return *(ptr + cols * i + j); 92 } 93 void Matrix::display() const { 94 int i, j; 95 int line = get_lines(); 96 int col = get_cols(); 97 for (i = 0; i < line; i++) { 98 for (j = 0; j < col; j++) { 99 cout << *(ptr + cols * i + j); 100 if (j != col - 1) { 101 cout << ","; 102 } 103 } 104 cout << endl; 105 } 106 } 107 108 109 110 111 #include "matrix.hpp" 112 #include <iostream> 113 #include <cassert> 114 115 using std::cin; 116 using std::cout; 117 using std::endl; 118 119 120 const int N = 1000; 121 122 // 輸出矩陣物件索引為index所在行的所有元素 123 void output(const Matrix &m, int index) { 124 assert(index >= 0 && index < m.get_lines()); 125 126 for(auto j = 0; j < m.get_cols(); ++j) 127 cout << m.at(index, j) << ", "; 128 cout << "\b\b \n"; 129 } 130 131 132 void test1() { 133 double x[1000] = {11, 12, 13, 14, 15, 16, 17, 18, 19}; 134 135 int n, m; 136 cout << "Enter n and m: "; 137 cin >> n >> m; 138 139 Matrix m1(n, m); // 建立矩陣物件m1, 大小n×m 140 m1.set(x); // 用一維陣列x的值按行為矩陣m1賦值 141 142 Matrix m2(m, n); // 建立矩陣物件m1, 大小m×n 143 m2.set(x); // 用一維陣列x的值按行為矩陣m1賦值 144 145 Matrix m3(2); // 建立一個2×2矩陣物件 146 m3.set(x); // 用一維陣列x的值按行為矩陣m4賦值 147 148 cout << "矩陣物件m1: \n"; m1.display(); cout << endl; 149 cout << "矩陣物件m2: \n"; m2.display(); cout << endl; 150 cout << "矩陣物件m3: \n"; m3.display(); cout << endl; 151 } 152 153 void test2() { 154 Matrix m1(2, 3); 155 m1.clear(); 156 157 const Matrix m2(m1); 158 m1.at(0, 0) = -999; 159 160 cout << "m1.at(0, 0) = " << m1.at(0, 0) << endl; 161 cout << "m2.at(0, 0) = " << m2.at(0, 0) << endl; 162 cout << "矩陣物件m1第0行: "; output(m1, 0); 163 cout << "矩陣物件m2第0行: "; output(m2, 0); 164 } 165 166 int main() { 167 cout << "測試1: \n"; 168 test1(); 169 170 cout << "測試2: \n"; 171 test2(); 172 }
結果:
任務5:
原始碼:
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 class User { 6 private: 7 string name; 8 string password; 9 string email; 10 public: 11 User(string n); 12 User(string n, string pw, string em); 13 ~User(); 14 void set_email(); 15 void change_password(); 16 void display()const; 17 }; 18 User::User(string n){ 19 name = n; 20 password = "123456"; 21 email = ""; 22 } 23 User::User(string n, string pw, string em) { 24 name = n; 25 password = pw; 26 email = em; 27 } 28 User::~User() {} 29 void User::set_email() { 30 cout << "Enter email address:"; 31 string em; 32 while (1) { 33 cin >> em; 34 if (em.find('@') == -1) { 35 cout << "illegal email.Please re-enter email:"; 36 continue; 37 } 38 email = em; 39 cout << "email is set successfully." << endl; 40 break; 41 } 42 } 43 void User::change_password() { 44 cout << "Enter old password:"; 45 string opw; 46 int cnt = 0; 47 while (1) { 48 cin >> opw; 49 if (opw.compare(password)) { 50 cnt++; 51 if (cnt >= 3) { 52 cout << "Try again later." << endl; 53 break; 54 } 55 cout << "Wrong.Please enter the true old password:"; 56 continue; 57 } 58 cout << "Enter new password:"; 59 cin >> password; 60 cout << "new password is set successfully." << endl; 61 break; 62 } 63 } 64 void User::display()const { 65 cout << "name:" << name << endl; 66 int i; 67 cout << "pass:"; 68 for (i = 0; i < password.size(); i++) { 69 cout << '*'; 70 } 71 cout << endl; 72 cout << "email:" << email << endl << endl; 73 } 74 75 76 77 #include "user.hpp" 78 #include <iostream> 79 #include <vector> 80 #include <string> 81 82 using std::cin; 83 using std::cout; 84 using std::endl; 85 using std::vector; 86 using std::string; 87 88 void test() { 89 vector<User> user_lst; 90 91 User u1("Alice", "2024113", "Alice@hotmail.com"); 92 user_lst.push_back(u1); 93 cout << endl; 94 95 User u2("Bob"); 96 u2.set_email(); 97 u2.change_password(); 98 user_lst.push_back(u2); 99 cout << endl; 100 101 User u3("Hellen"); 102 u3.set_email(); 103 u3.change_password(); 104 user_lst.push_back(u3); 105 cout << endl; 106 107 cout << "There are " << user_lst.size() << " users. they are: " << endl; 108 for (auto& i : user_lst) { 109 i.display(); 110 cout << endl; 111 } 112 } 113 114 int main() { 115 test(); 116 }
結果:
任務6:
原始碼:
1 #ifndef _ _ACCOUNT_H_ _ 2 #define _ _ACCOUNT_H_ _ 3 #include"date.h" 4 #include<string> 5 class SavingsAccount { 6 private: 7 std::string id; 8 double balance; 9 double rate; 10 Date lastDate; 11 double accumulation; 12 static double total; 13 void record(const Date& date, double amount, const std::string& desc); 14 void error(const std::string& msg) const; 15 double accumulate(const Date& date)const { 16 return accumulation + balance * date.distance(lastDate); 17 18 } 19 public: 20 SavingsAccount(const Date& date, const std::string& id, double rate); 21 const std::string& getId()const { return id; } 22 double getBalance()const { return balance; } 23 double getRate()const { return rate; } 24 static double getTotal() { return total; } 25 void deposit(const Date& date, double amount, const std::string& desc); 26 void withdraw(const Date& date, double amount, const std::string& desc); 27 void settle(const Date& date); 28 void show()const; 29 }; 30 #endif //_ _ACCOUNT_H_ _
1 class Date { 2 private: 3 int year; 4 int month; 5 int day; 6 int totalDays; 7 public: 8 Date(int year, int month, int day); 9 int getYear() const { return year; } 10 int getMonth()const { return month; } 11 int getDay()const { return day; } 12 int getMaxDay()const; 13 bool isLeapYear()const { 14 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 15 } 16 void show() const; 17 int distance(const Date& date)const { 18 return totalDays - date.totalDays; 19 } 20 };
1 #include"account.h" 2 #include<cmath> 3 #include<iostream> 4 using namespace std; 5 double SavingsAccount::total = 0; 6 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) 7 :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) { 8 date.show(); 9 cout << "\t#" << id << "created" << endl; 10 11 } 12 void SavingsAccount::record(const Date& date, double amount, const string& desc) { 13 accumulation = accumulate(date); 14 lastDate = date; 15 amount = floor(amount * 100 + 0.5) / 100; 16 balance -= amount; 17 total += amount; 18 date.show(); 19 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 20 21 } 22 void SavingsAccount::error(const string& msg)const { 23 cout << "Error(#" << id << "):" << msg << endl; 24 } 25 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 26 record(date, amount, desc); 27 } 28 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 29 if (amount > getBalance()) 30 error("not enough money"); 31 else 32 record(date, -amount, desc); 33 34 } 35 void SavingsAccount::settle(const Date& date) { 36 double interest = accumulate(date) * rate 37 / date.distance(Date(date.getYear() - 1, 1, 1)); 38 if (interest != 0) 39 record(date, interest, "interest"); 40 accumulation = 0; 41 42 } 43 void SavingsAccount::show()const { 44 cout << id << "\tBalance:" << balance; 45 }
1 #include"date.h" 2 #include<iostream> 3 #include<cstdlib> 4 using namespace std; 5 namespace { 6 const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 }; 7 } 8 Date::Date(int year, int month, int day) :year(year), month(month), day(day) { 9 if (day <= 0 || day > getMaxDay()) { 10 cout << "Invalid date: "; 11 show(); 12 cout << endl; 13 exit(1); 14 } 15 int years = year - 1; 16 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day; 17 if (isLeapYear() && month > 2)totalDays++; 18 } 19 int Date::getMaxDay()const { 20 if (isLeapYear() && month == 2) 21 return 29; 22 else 23 return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1]; 24 } 25 void Date::show()const { 26 cout << getYear() << "-" << getMonth() << "-" << getDay(); 27 }
1 #include"account.h" 2 #include<iostream> 3 using namespace std; 4 int main() { 5 Date date(2008, 11, 1); 6 SavingsAccount accounts[] = { 7 SavingsAccount(date,"03755217",0.015), 8 SavingsAccount(date,"02342342",0.015) 9 10 }; 11 const int n = sizeof(accounts) / sizeof(SavingsAccount); 12 accounts[0].deposit(Date(2008, 11, 5), 5000, "salary"); 13 accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); 14 accounts[0].deposit(Date(2008, 12, 5), 5500, "salary"); 15 accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop"); 16 cout << endl; 17 for (int i = 0; i < n; i++) { 18 accounts[i].settle(Date(2009, 1, 1)); 19 accounts[i].show(); 20 cout << endl; 21 } 22 cout << "Total:" << SavingsAccount::getTotal() << endl; 23 return 0; 24 }
結果: