實驗3 類和物件

易安135發表於2024-11-10

實驗任務1

button.hpp

實驗3 類和物件
 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 }
View Code

window.hpp

實驗3 類和物件
 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 }
View Code

task1.cpp

實驗3 類和物件
 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 }
View Code

問題一:定義了window和button兩個類,使用了標準庫的string、vector、iostream類

問題二:不需要加const和inline 因為這些成員函式呼叫的時候不會對資料造成改變,而且其呼叫頻率比較低,不需要變成行內函數

問題三:其功能是建立一個長度為30的字串,每一個字元都是*

實驗任務2

實驗3 類和物件
 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 }
View Code

問題一:第21行的程式碼是建立了一個名為v1的vector,包含五個元素,每個元素都是42

     第22行的程式碼時建立了一個名為v2的vector,透過複製v1來初始化

     第24行的程式碼是把v1的第0個元素改成-999,不影響v2

問題二:第32行程式碼建立了一個名為v1的二維vector

    第33行程式碼建立了一個名為v2的二維vector,它透過複製v1來初始化,且值不能改變

    第35行程式碼在v1索引為0的vector最後加一個元素-999

問題三:第39行程式碼建立了一個名為t1的int型別的vector,透過複製v1的第一個vector來初始化

第40行程式碼輸出了t1最後一個元素的值

第42行程式碼建立了一個名為t2的int型別的vector,透過複製v2的第一個vector來初始化 ,且值不能被改變

第43行程式碼輸出了t2最後一個元素的值

問題四:1、模板庫內部封裝的複製建構函式是淺複製;2、我覺得至少需要提供一個const成員作為介面,從而保證內部資料不易被改變

實驗任務3

vectorInt.hpp

實驗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 }
View Code

task3.cpp

實驗3 類和物件
 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 }
View Code

問題1:line14是深複製

問題2:將int&改成int後不能正常執行,at介面原來返回的是引用,允許直接修改元素值,改為int後返回的是值,意味著返回的是元素的複製,對原容器中值沒有影響。line18前面的const刪除返回值就變成了int&,允許修改元素值,與const成員函式相違背,存在安全隱患。

問題3:可以,但是不建議。返回一個新值可能會造成資源洩露,因為原物件中的資源在返回新物件後沒有被正確釋放。

實驗任務4

Matrix.hpp

實驗3 類和物件
 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::Matrix(int n,int m):lines{n},cols{m}{
35     ptr=new double[n*m]; 
36 }
37 Matrix::Matrix(int n){
38     ptr=new double[n*n];
39 }
40 Matrix::~Matrix(){
41     delete []ptr;
42 }
43 void Matrix::clear(){
44     for(int i=0;i<lines*cols;++i){
45         ptr[i]=0;
46     }
47 }
48 void Matrix::set(const double* pvalue){
49     for(int i=0;i<lines*cols;i++){
50         ptr[i]=pvalue[i];
51     }
52 }
53 Matrix::Matrix(const Matrix &x):lines{x.lines},cols{x.cols}{
54     ptr=new double[lines*cols];
55     for(int i=0;i<lines*cols;i++){
56         ptr[i]=x.ptr[i];
57     }
58 }
59 const double& Matrix::at(int i,int j)const {
60     return ptr[i*cols+j];
61 }
62 double& Matrix::at(int i,int j){
63     return ptr[i*cols+j];
64 }
65 int Matrix::get_lines()const{
66     return lines;
67 }
68 int Matrix::get_cols()const{
69     return cols;
70 }
71 void Matrix::display()const{
72     for(int i=0;i<lines*cols;i++){
73         if((i+1)%cols!=0){
74             cout<<ptr[i]<<" ,";
75         }else{
76             cout<<ptr[i]<<endl;
77         }
78     }
79 }
View Code
實驗3 類和物件
 1 #include "matrix.hpp"
 2 #include <iostream>
 3 #include <cassert>
 4 
 5 using std::cin;
 6 using std::cout;
 7 using std::endl;
 8 
 9 
10 const int N = 1000;
11 
12 // 輸出矩陣物件索引為index所在行的所有元素
13 void output(const Matrix &m, int index) {
14     assert(index >= 0 && index < m.get_lines());
15 
16     for(auto j = 0; j < m.get_cols(); ++j)
17         cout << m.at(index, j) << ", ";
18     cout << "\b\b \n";
19 }
20 
21 
22 void test1() {
23     double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
24 
25     int n, m;
26     cout << "Enter n and m: ";
27     cin >> n >> m;
28 
29     Matrix m1(n, m);    // 建立矩陣物件m1, 大小n×m
30     m1.set(x);          // 用一維陣列x的值按行為矩陣m1賦值
31 
32     Matrix m2(m, n);    // 建立矩陣物件m1, 大小m×n
33     m2.set(x);          // 用一維陣列x的值按行為矩陣m1賦值
34 
35     Matrix m3(2);       // 建立一個2×2矩陣物件
36     m3.set(x);          // 用一維陣列x的值按行為矩陣m4賦值
37 
38     cout << "矩陣物件m1: \n";   m1.display();  cout << endl;
39     cout << "矩陣物件m2: \n";   m2.display();  cout << endl;
40     cout << "矩陣物件m3: \n";   m3.display();  cout << endl;
41 }
42 
43 void test2() {
44     Matrix m1(2, 3);
45     m1.clear();
46     
47     const Matrix m2(m1);
48     m1.at(0, 0) = -999;
49 
50     cout << "m1.at(0, 0) = " << m1.at(0, 0) << endl;
51     cout << "m2.at(0, 0) = " << m2.at(0, 0) << endl;
52     cout << "矩陣物件m1第0行: "; output(m1, 0);
53     cout << "矩陣物件m2第0行: "; output(m2, 0);
54 }
55 
56 int main() {
57     cout << "測試1: \n";
58     test1();
59 
60     cout << "測試2: \n";
61     test2();
62 }
View Code

實驗任務5

user.hpp

實驗3 類和物件
 1 #pragma once
 2 #include<iostream>
 3 #include<vector>
 4 using namespace std;
 5 using std::endl;
 6 using std::cin;
 7 using std::cout;
 8 using std::string;
 9 class User{
10 public:
11     User(string Name,string Password="123456",string Email="");
12     void set_email();
13     void change_password();
14     void display() const;
15 private:
16     string name,password,email;
17 };
18 
19 User::User(string Name,string Password,string Email):name(Name),password(Password),email(Email){};
20 void set_email(){
21     cout<<"Enter email address:";
22     string email1;
23     int flag=1;
24     while(1){
25         cin>>email1;
26         flag=1;
27         if(email1.find("@")!=-1){
28             flag=0;
29         }
30         if (flag==0) {
31             break;
32         }
33         else{
34             cout<<"illegal email.Please re-enter email:";
35         }
36     }email=email1;
37     cout<<"email is set successfully..."<<endl;
38 }
39 
40 void change_password(){
41     cout<<"Enter old password:";
42     int count,flag=1;
43     while(1){
44         string password1;
45         if(password1!=password){
46             cout<<"password input error.Please re-enter again:";
47             count++;
48         }else{
49             break;
50         }if(count==3){
51             cout<<"password input error.Please try after a while."<<endl;
52             flag=0;
53             break;
54         }
55     }if (flag){
56         cout<<"Enter new password:";
57         cin>>password;
58         cout<<"new password is set successfully..."<<endl;
59     }
60 }
61 void display()const{
62     int length=0;
63     length=password.size();
64     string str(length,'*');
65     cout<<"name:  " <<name<<endl;
66     cout<<"pass:  " <<password<<endl;
67     cout<<"email:  "<<email<<endl;
68     cout<<endl;
69 }
View Code

task5.cpp

實驗3 類和物件
 1 #include "user.hpp"
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 
 6 using std::cin;
 7 using std::cout;
 8 using std::endl;
 9 using std::vector;
10 using std::string;
11 
12 void test() {
13     vector<User> user_lst;
14 
15     User u1("Alice", "2024113", "Alice@hotmail.com");
16     user_lst.push_back(u1);
17     cout << endl;
18 
19     User u2("Bob");
20     u2.set_email();
21     u2.change_password();
22     user_lst.push_back(u2);
23     cout << endl;
24 
25     User u3("Hellen");
26     u3.set_email();
27     u3.change_password();
28     user_lst.push_back(u3);
29     cout << endl;
30 
31     cout << "There are " << user_lst.size() << " users. they are: " << endl;
32     for(auto &i: user_lst) {
33         i.display();
34         cout << endl;
35     }
36 }
37 
38 int main() {
39     test();
40 }
View Code

實驗任務6

account.h

實驗3 類和物件
 1 #ifndef __ACCOUNT_H__
 2 #define __ACCOUNT_H__
 3 #include "date.h"
 4 #include <string>
 5 class SavingsAccount {
 6 
 7 private:
 8     std::string id;
 9     double balance,rate,accumulation;
10     Date lastDate;
11     static double total;
12 
13     void record(const Date& date, double amount, const std::string& desc);
14 
15     void error(const std::string& msg) const;
16 
17     double accumulate(const Date& date) const {
18         return accumulation + balance * date.distance(lastDate);
19     }
20 public:
21     SavingsAccount(const Date& date, const std::string& id, double rate);
22     const std::string& getId() const { return id; }
23     double getBalance() const { return balance; }
24     double getRate() const { return rate; }
25     static double getTotal() { return total; }
26 
27     void deposit(const Date& date, double amount, const std::string& desc);
28 
29     void withdraw(const Date& date, double amount, const std::string& desc);
30 
31     void settle(const Date& date);
32 
33     void show() const;
34 };
35 #endif
View Code

account.cpp

實驗3 類和物件
 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) :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
 7     date.show();
 8     cout << "\t#" << id << "created" << endl;
 9 }
10 void SavingsAccount::record(const Date& date, double amount, const string& desc) {
11     accumulation = accumulate(date);
12     lastDate = date;
13     amount = floor(amount * 100 + 0.5) / 100;
14     balance += amount;
15     total += amount;
16     date.show();
17     cout << "t\#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
18 }
19 void SavingsAccount::error(const string& msg) const {
20     cout << "Error(# " << id << " ):" << msg << endl;
21 }
22 void SavingsAccount::deposit(const Date & date, double amount, const string & desc) {
23     record(date, amount, desc);
24 }
25 void SavingsAccount::withdraw(const Date & date, double amount, const string& desc) {
26     if (amount > getBalance())
27         error("not enough money");
28     else
29         record(date, -amount, desc);
30 }
31 void SavingsAccount::settle(const Date& date) {
32     double interest = accumulate(date) * rate//計算年息
33         / date.distance(Date(date.getYear() - 1, 1, 1));
34     if (interest != 0)
35         record(date, interest, "interest");
36     accumulation = 0;
37 }
38 void SavingsAccount::show() const {
39     cout << id << "\tBalance:" << balance;
40 }
View Code

date.h

實驗3 類和物件
 1 #ifndef __DATE_H__
 2 #define __DATE_H__
 3 class Date{
 4     private:
 5         int year,month,day,totalDays;
 6     public:
 7         Date(int year,int month,int day);
 8         int getYear()const{return year;}
 9         int getMonth()const{return month;}
10         int getDay() const{return day;}
11         int getMaxDay() const;
12         bool isLeapYear()const{
13             return year%4==0 && year%100!=0 ||year%400==0;
14         }
15         void show()const;
16         int distance(const Date &date)const{
17             return totalDays-date.totalDays;
18         }
19         
20 };
21 #endif / / _DATE_H__
View Code

date.cpp

實驗3 類和物件
 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 }
View Code

6.25.cpp

實驗3 類和物件
 1 #include "account.h"
 2 #include <iostream>
 3 using namespace std;
 4 int main() {
 5     //起始日期
 6     Date date(2008, 11, 1);
 7     //建立幾個賬戶
 8     SavingsAccount accounts[] = {
 9     SavingsAccount(date,"03755217",0.015),
10     SavingsAccount(date, "02342342", 0.015)
11     };
12     const int n = sizeof(accounts) / sizeof(SavingsAccount); //賬戶總數
13 
14     accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
15     accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
16 
17     accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
18     accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");
19 
20     cout << endl;
21     for (int i = 0; i < n; i++) {
22         accounts[i].settle(Date(2009, 1, 1));
23         accounts[i].show();
24         cout << endl;
25     }
26     cout << "Total: " << SavingsAccount::getTotal() << endl;
27     return 0;
28 }
View Code

相關文章