实验3 类和对象_基础编程2

实验任务1

代码

button.hpp

 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 }

window.hpp

 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 class Window{
11 public:
12     Window(const string &win_title);
13     void display() const;
14     void close();
15     void add_button(const string &label);
16 
17 private:
18     string title;
19     vector<Button> buttons;
20 };
21 
22 Window::Window(const string &win_title): title{win_title} {
23     buttons.push_back(Button("close"));
24 }
25 
26 inline void Window::display() const {
27     string s(40, '*');
28 
29     cout << s << endl;
30     cout << "window title: " << title << endl;
31     cout << "It has " << buttons.size() << " buttons: " << endl;
32     for(const auto &i: buttons)
33         cout << i.get_label() << " button" << endl;
34     cout << s << endl;
35 }
36 
37 void Window::close() {
38     cout << "close window '" << title << "'" << endl;
39     buttons.at(0).click();
40 }
41 
42 void Window::add_button(const string &label) {
43     buttons.push_back(Button(label));
44 }

task1.cpp

 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 }#pragma once
30 #include "button.hpp"
31 #include <vector>
32 #include <iostream>
33 
34 using std::vector;
35 using std::cout;
36 using std::endl;
37 
38 class Window{
39 public:
40     Window(const string &win_title);
41     void display() const;
42     void close();
43     void add_button(const string &label);
44 
45 private:
46     string title;
47     vector<Button> buttons;
48 };
49 
50 Window::Window(const string &win_title): title{win_title} {
51     buttons.push_back(Button("close"));
52 }
53 
54 inline void Window::display() const {
55     string s(40, '*');
56 
57     cout << s << endl;
58     cout << "window title: " << title << endl;
59     cout << "It has " << buttons.size() << " buttons: " << endl;
60     for(const auto &i: buttons)
61         cout << i.get_label() << " button" << endl;
62     cout << s << endl;
63 }
64 
65 void Window::close() {
66     cout << "close window '" << title << "'" << endl;
67     buttons.at(0).click();
68 }
69 
70 void Window::add_button(const string &label) {
71     buttons.push_back(Button(label));
72 }
73 
74 #include "window.hpp"
75 #include <iostream>
76 
77 using std::cout;
78 using std::cin;
79 
80 void test() {
81     Window w1("new window");
82     w1.add_button("maximize");
83     w1.display();
84     w1.close();
85 }
86 
87 int main() {
88     cout << "用组合类模拟简单GUI:\n";
89     test();
90 }

运行结果

问题1

自定义了两个类:Button和Window。

使用到了标注库的两个类:string和vector。

Window和Button之间有组合关系,Window类包含一个vector<Button>成员变量buttons,表示window拥有多个button。

问题2

适合添加const的函数:
在Window类中,display()函数是一个仅用于展示Window状态的操作,不会修改Window对象的任何数据成员。因此,它可以被合理地设置为const。
Button类中的get_label()函数返回按钮标签,并且不修改任何数据成员,因此也可以被合理地设置为const。
适合添加 inline 的函数:
get_label()函数是一个简单的访问器函数,其实现相对简单且行数较少,符合内联函数的应用场景,因此它可以被合理设置为inline。
display()函数虽被设置为inline,但由于其输出逻辑较多,适合作为非内联函数,以避免占用过多的代码空间。
不适合添加const和inline的函数:
click()函数会输出点击信息,因此不适合添加const。
close()函数会修改buttons,因此不适合添加const。

问题3

这行代码的功能是创建一个字符串对象s,它包含40个星号字符(*),用于在display() 函数中作为装饰线条打印窗口标题等信息。

 

实验任务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

vector的深复制表现为:v1和v2独立,修改v1不影响v2。
问题2

vector的深复制机制。
问题3

接口at()的const修饰。

问题4

1.vector的复制构造函数实现了深复制。在test2()中,我们创建了vector<vector<int>>类型的v1和v2。虽然v2是通过v1复制构造得到的,但当我们修改v1中的元素时(例如在第一行向量中添加 -999),v2中的数据保持不变。这表明 v2拷贝了v1的内容,而非指针或引用,因此是深复制。

2.是的,vector的at()接口需要提供一个const成员函数。const成员函数允许在只读的上下文中安全地访问vector的元素。例如,在output1和output2函数中,参数是const vector<int>&和const vector<vector<int>>&,这些函数要求 at()方法能够用于const对象。因此,提供const重载可以保证vector在只读和可修改的场景下都能被安全地访问。

 

实验任务3

代码

vectorlnt.hpp

 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 }

task3.cpp

 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 的复制构造实现了深复制。

问题2

at() 返回值为 int& 是必要的。

问题3

assign() 的返回类型保持 vectorInt& 符合 C++ 规范。

 

实验任务4

代码

matric.hpp

 1 #pragma once
 2 #include <iostream>
 3 #include <cassert>
 4 
 5 using std::cout;
 6 using std::endl;
 7 
 8 class Matrix {
 9 public:
10     Matrix(int n, int m);        // 构造 n×m 矩阵
11     Matrix(int n);               // 构造 n×n 矩阵
12     Matrix(const Matrix &x);     // 复制构造函数
13     ~Matrix();
14 
15     void set(const double *pvalue); // 用pvalue的值按行赋值
16     void clear();                   // 将矩阵置0
17     const double& at(int i, int j) const;
18     double& at(int i, int j);
19     int get_lines() const;
20     int get_cols() const;
21     void display() const;
22 
23 private:
24     int lines;      // 行数
25     int cols;       // 列数
26     double *ptr;    // 指向矩阵数据的指针
27 };
28 
29 Matrix::Matrix(int n, int m) : lines{n}, cols{m}, ptr{new double[n * m]()} {}
30 
31 Matrix::Matrix(int n) : Matrix(n, n) {}
32 
33 Matrix::Matrix(const Matrix &x) : lines{x.lines}, cols{x.cols}, ptr{new double[lines * cols]} {
34     for(int i = 0; i < lines * cols; ++i)
35         ptr[i] = x.ptr[i];
36 }
37 
38 Matrix::~Matrix() {
39     delete[] ptr;
40 }
41 
42 void Matrix::set(const double *pvalue) {
43     for(int i = 0; i < lines * cols; ++i)
44         ptr[i] = pvalue[i];
45 }
46 
47 void Matrix::clear() {
48     for(int i = 0; i < lines * cols; ++i)
49         ptr[i] = 0;
50 }
51 
52 double& Matrix::at(int i, int j) {
53     assert(i >= 0 && i < lines && j >= 0 && j < cols);
54     return ptr[i * cols + j];
55 }
56 
57 const double& Matrix::at(int i, int j) const {
58     assert(i >= 0 && i < lines && j >= 0 && j < cols);
59     return ptr[i * cols + j];
60 }
61 
62 int Matrix::get_lines() const { return lines; }
63 int Matrix::get_cols() const { return cols; }
64 
65 void Matrix::display() const {
66     for(int i = 0; i < lines; ++i) {
67         for(int j = 0; j < cols; ++j)
68             cout << at(i, j) << " ";
69         cout << endl;
70     }
71 }

task4.cpp

 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] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
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 }

运行结果

 

实验任务5

代码

user.hpp

 1 #ifndef USER_HPP
 2 #define USER_HPP
 3 
 4 #include <iostream>
 5 #include <string>
 6 #include <limits>
 7 
 8 class User {
 9 private:
10     std::string name;     // 用户名
11     std::string password; // 密码
12     std::string email;    // 邮箱
13 
14 public:
15     // 构造函数
16     User(const std::string& name0, const std::string& password0 = "123456", const std::string& mail0 = "")
17         : name(name0), password(password0), email(mail0) {}
18 
19     // 接口1,用来提示设置邮箱
20     void set_email() {
21     std::string test_email;
22 
23     while (true) {
24         std::cout << "Enter email address: ";
25         std::cin >> test_email;
26 
27         if (test_email.find('@') == std::string::npos) {
28             std::cout << "Illegal email. Please re-enter email: ";
29         } else {
30             email = test_email;
31             std::cout << "Email is set successfully..." << std::endl;
32             break;
33         }
34     }
35 }
36 
37     // 接口2,用来修改密码
38     void change_password() {
39         std::string old_password, new_password; // 定义 new_password
40         int attempts = 0;
41         const int max_attempts = 3;
42 
43         while (attempts < max_attempts) {
44             std::cout << "Enter old password: ";
45             std::cin >> old_password;
46 
47             if (old_password == password) {
48                 std::cout << "Enter new password: ";
49                 std::cin >> new_password;
50                 password = new_password;
51                 std::cout << "new password is set successfully..." << std::endl;
52                 return;
53             } else {
54                 attempts++;
55 
56                 if (attempts == max_attempts) {
57                     std::cout << "password input error. Please try after a while." << std::endl;
58                 } else {
59                     std::cout << "password input error. Please re-enter again." << std::endl;
60                 }
61 
62             }
63         }
64     }
65 
66     // 接口3,用来打印用户信息
67     void display() const {
68         std::cout << "name: " << name << "\n";
69         std::cout << "pass: ";
70         for (int i = 0; i < password.length(); ++i) {
71             std::cout << "*";
72         }
73         std::cout << std::endl;
74         std::cout << "email: " << email << std::endl;
75     }
76 };
77 
78 #endif

task5.cpp

 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 }

运行结果

 

实验任务6

代码

date.h

 1 #ifndef __DATE_H__
 2 #define __DATE_H__
 3 
 4 class Date {
 5 private:
 6     int year;    //
 7     int month;   //
 8     int day;     //
 9     int totalDays; //该日期是从公元元年1月1日开始的第几天
10 public:
11     Date(int year, int month, int day); //用年、月、日构造日期
12     int getYear() const { return year; }
13     int getMonth() const { return month; }
14     int getDay() const { return day; }
15     int getMaxDay() const;
16     bool isLeapYear() const {
17         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
18     }
19     void show() const;
20     //计算两个日期之间相差多少天
21     int distance(const Date& date) const {
22         return totalDays - date.totalDays;
23     }
24 };
25 #endif

date.cpp

 1 #include "date.h"
 2 #include <iostream>
 3 #include <cstdlib>
 4 using namespace std;
 5 
 6 //命名空间使下面的定义只在当前文件中有效
 7 namespace {
 8     //存储平年中的某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
 9     const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
10 }
11 
12 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
13     if (day <= 0 || day > getMaxDay()) {
14         cout << "Invalid date.";
15         show();
16         cout << endl;
17         exit(1);
18     }
19     int years = year - 1;
20     totalDays = years * 365 + years / 4 - years / 100 + years / 400
21         + DAYS_BEFORE_MONTH[month-1] + day;
22     if (isLeapYear() && month > 2) totalDays++;
23 }
24 
25 
26 int Date::getMaxDay()const {
27     if (isLeapYear() && month == 2) {
28         return 29;
29     }
30     else {
31         return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
32     }
33 }
34 
35 void Date::show() const {
36     cout << getYear() << '-' << getMonth() << '-' << getDay();
37 }

account.h

 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     //记录一笔帐,date为日期,amount为金额,desc为说明
14     void record(const Date& date, double amount, const std::string& desc);
15     //报告错误信息
16     void error(const std::string& msg) const;
17     //获得指定日期为止的存款金额按日累积值
18     double accumulate(const Date& date) const {
19         return accumulation + balance * date.distance(lastDate);
20     }
21 public:
22     //构造函数
23     SavingsAccount(const Date& date, const std::string& id, double rate);
24     const std::string& getId() const { return id; }
25     double getBalance() const { return balance; }
26     double getRate() const { return rate; }
27     static double getTotal() { return total; }
28     //存入现金
29     void deposit(const Date& date, double amount, const std::string& desc);
30     //取出现金
31     void withdraw(const Date& date, double amount, const std::string& desc);
32     //结算利息,每年1月1日调用一次该函数
33     void settle(const Date& date);
34     //显示账户信息
35     void show() const;
36 };
37 #endif // ACCOUNT_H

account.cpp

 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 std::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 std::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 std::string& msg) const {
20     cout << "Error(#" << id << "): " << msg << endl;
21 }
22 
23 void SavingsAccount::deposit(const Date& date, double amount, const std::string& desc) {
24     record(date, amount, desc);
25 }
26 
27 void SavingsAccount::withdraw(const Date& date, double amount, const std::string& desc) {
28     if (amount > getBalance())
29         error("not enough money");
30     else
31         record(date, -amount, desc);
32 }
33 
34 void SavingsAccount::settle(const Date& date) {
35     double interest = accumulate(date) * rate /date.distance(Date(date.getYear()-1,1,1));
36     if (interest != 0)
37         record(date, interest, "interest");
38     accumulation = 0;
39 }
40 
41 void SavingsAccount::show() const {
42     cout << id << "\tBalance: " << balance;
43 }

6_25.cpp

 1 #include "account.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main() {
 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     //11月份的几笔账目
14     accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
15     accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
16     //12月份的几笔账目
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 }

运行结果

 

posted @ 2024-11-11 11:17  臣子民  阅读(3)  评论(0编辑  收藏  举报