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

实验任务一

代码

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 // ´°¿ÚÀà
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 }

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 }

task1.cpp

 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: 

自定义了两个类,Button和Window;使用到了std::string和std::vector。;Window类与Button类之间存在组合关系。

问题2: 

const关键字用于那些不修改对象状态的成员函数。Button::get_label被声明为const,因为它仅返回Button的标签而不修改任何成员变量。Window::display同样被声明为const,因为它只是显示窗口和按钮信息而不改变任何状态。;

Button::click可以加const,因为它输出信息但不改变Button的状态

Button::click和Window::add_button等因为包含逻辑较多的操作,不适宜设置为inline。

问题3:定义一个长度为48的类型的字符串,元素都为“*”;

 

实验任务二

代码

 

 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:

21  vector<int> v1(5, 42); // 创建一个包含5个整数的vector,每个整数初始化为42

22  vector<int> v2(v1);    // 通过复制构造函数创建v2,v2是v1的深拷贝

23  v1.at(0) = -999;       // 通过at成员函数访问v1的第一个元素,并将其值设置为-999

问题2:

32  vector<vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}}; // 创建一个包含两个vector<int>的vector,第一个有三个元素,第二个有四个元素

33  const vector<vector<int>> v2(v1);                // 通过复制构造函数创建v2,v2是v1的深拷贝

35  v1.at(0).push_back(-999);                        // 访问v1中的第一个vector,并在其末尾添加一个整数-999

问题3:

39  vector<int> t1 = v1.at(0); // 通过复制构造函数,从v1中获取第一个vector的一个拷贝

40  cout << t1.at(t1.size()-1) << endl; // 打印t1中最后一个元素,也就是-999

42  const vector<int> t2 = v2.at(0); // 从v2中获取第一个vector的一个const拷贝

43  cout << t2.at(t2.size()-1) << endl; // 打印t2中最后一个元素,应为3,因为v2是v1复制前的状态的拷贝

问题4:

1.深复制。在第一测试中,v1和v2是独立的;修改v1不影响v2。在第二测试中,修改v1中的一个子vector也不影响v2中相应的子vector,说明v2是v1的完全独立拷贝。

2.至少需要提供一个const成员函数作为接口

 

 实验任务3

代码

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 }

vectorInt.hpp

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <cassert>
 5 
 6 using std::cout;
 7 using std::endl;
 8 
 9 class vectorInt{
10 public:
11     vectorInt(int n);
12     vectorInt(int n, int value);
13     vectorInt(const vectorInt &vi);
14     ~vectorInt();
15 
16     int& at(int index);
17     const int& at(int index) const;
18 
19     vectorInt& assign(const vectorInt &v);
20     int get_size() const;
21 
22 private:
23     int size;
24     int *ptr;     
25 };
26 
27 vectorInt::vectorInt(int n): size{n}, ptr{new int[size]} {
28 }
29 
30 vectorInt::vectorInt(int n, int value): size{n}, ptr{new int[size]} {
31     for(auto i = 0; i < size; ++i)
32         ptr[i] = value;
33 }
34 
35 vectorInt::vectorInt(const vectorInt &vi): size{vi.size}, ptr{new int[size]} {
36     for(auto i = 0; i < size; ++i)
37         ptr[i] = vi.ptr[i];
38 }
39 
40 vectorInt::~vectorInt() {
41     delete [] ptr;
42 }
43 
44 const int& vectorInt::at(int index) const {
45     assert(index >= 0 && index < size);
46 
47     return ptr[index];
48 }
49 
50 int& vectorInt::at(int index) {
51     assert(index >= 0 && index < size);
52 
53     return ptr[index];
54 }
55 
56 vectorInt& vectorInt::assign(const vectorInt &v) {  
57     delete[] ptr;     
58 
59     size = v.size;
60     ptr = new int[size];
61 
62     for(int i = 0; i < size; ++i)
63         ptr[i] = v.ptr[i];
64 
65     return *this;
66 }
67 
68 int vectorInt::get_size() const {
69     return size;
70 }

 

编译结果

 

问题:

问题1:

是深复制。

问题2:

测试代码将无法正常工作,尤其是所有想通过 at() 修改数组中元素的地方都会出现错误。

const 成员函数的目的是保证函数调用不会修改类的内部状态,包括其成员变量。去掉 const 会导致 const vectorInt 对象无法调用该方法,因为它会破坏常量对象的不可变性。所以这种情况下会存在潜在的安全隐患,因为违反了常量对象的访问规则,可能会导致不可预测的行为。

问题3:

如果将返回类型改为 vectorInt,则会返回一个新的对象副本,而不是对原对象本身的引用,这样的话链式操作将无法进行,因为每次调用都会产生一个新的对象而不是对当前对象的引用。此外,频繁创建新的对象也会导致不必要的内存分配,降低程序的效率。因此,将返回类型改为 vectorInt 会导致 无法实现链式调用,且增加不必要的性能开销,因此不是合适的选择。

 

实验任务4

代码

matrix.hpp

 1 #pragma once
 2 #include <iostream>
 3 #include <cassert>
 4 
 5 using std::cout;
 6 using std::endl;
 7 
 8 // 类Matrix的声明和实现
 9 class Matrix {
10 public:
11     Matrix(int n, int m); // 构造函数,构造一个n*m的矩阵
12     Matrix(int n); // 构造函数,构造一个n*n的矩阵
13     Matrix(const Matrix &x); // 复制构造函数, 使用已有的矩阵X构造
14     ~Matrix(); // 析构函数
15     void set(const double *pvalue); // 用pvalue指向的连续内存块数据按行赋值
16     void clear(); // 把矩阵对象的值置0
17     const double& at(int i, int j) const; // 返回矩阵对象索引(i, j)的元素 const 引用
18     double& at(int i, int j); // 返回矩阵对象索引(i, 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 // 构造一个n*m的矩阵
30 Matrix::Matrix(int n, int m) : lines{n}, cols{m}, ptr{new double[n * m]} {
31     for (int i = 0; i < lines * cols; ++i) {
32         ptr[i] = 0.0;
33     }
34 }
35 
36 // 构造一个n*n的矩阵
37 Matrix::Matrix(int n) : Matrix(n, n) {}
38 
39 // 复制构造函数,实现深复制
40 Matrix::Matrix(const Matrix &x) : lines{x.lines}, cols{x.cols}, ptr{new double[x.lines * x.cols]} {
41     for (int i = 0; i < lines * cols; ++i) {
42         ptr[i] = x.ptr[i];
43     }
44 }
45 
46 // 析构函数,释放动态内存
47 Matrix::~Matrix() {
48     delete[] ptr;
49 }
50 
51 // 用pvalue指向的连续内存块数据按行赋值
52 void Matrix::set(const double *pvalue) {
53     for (int i = 0; i < lines * cols; ++i) {
54         ptr[i] = pvalue[i];
55     }
56 }
57 
58 // 把矩阵对象的值置0
59 void Matrix::clear() {
60     for (int i = 0; i < lines * cols; ++i) {
61         ptr[i] = 0.0;
62     }
63 }
64 
65 // 返回矩阵对象索引(i, j)的元素的const引用
66 const double& Matrix::at(int i, int j) const {
67     assert(i >= 0 && i < lines);
68     assert(j >= 0 && j < cols);
69     return ptr[i * cols + j];
70 }
71 
72 // 返回矩阵对象索引(i, j)的元素引用
73 double& Matrix::at(int i, int j) {
74     assert(i >= 0 && i < lines);
75     assert(j >= 0 && j < cols);
76     return ptr[i * cols + j];
77 }
78 
79 // 返回矩阵对象的行数
80 int Matrix::get_lines() const {
81     return lines;
82 }
83 
84 // 返回矩阵对象的列数
85 int Matrix::get_cols() const {
86     return cols;
87 }
88 
89 // 按行显示矩阵对象元素值
90 void Matrix::display() const {
91     for (int i = 0; i < lines; ++i) {
92         for (int j = 0; j < cols; ++j) {
93             cout << at(i, j) << " ";
94         }
95         cout << endl;
96     }
97 }

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] = {12, 23, 34, 45, 56, 67, 78, 89, 91};
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

代码

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 }

user.hpp

#pragma once
#include <iostream>
#include <string>
#include <cassert>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class User {
public:
    User(const string& name, const string& password = "123456", const string& email = "")
        : name{name}, password{password}, email{email} {}

    void set_email() {
        while (true) {
            cout << "Enter email address: ";
            cin >> email;
            if (is_valid_email(email)) {
                cout << "email is set successfully...\n";
                break;
            } else {
                cout << "illegal email. Please re-enter email: ";
            }
        }
    }

    // 修改密码
    void change_password() {
        string old_password;
        int attempts = 0;
        while (attempts < 3) {
            cout << "Enter old password: ";
            cin >> old_password;
            if (old_password == password) {
                string new_password;
                cout << "Enter new password: ";
                cin >> new_password;
                password = new_password;
                cout << "new password is set successfully...\n";
                return;
            } else {
                attempts++;
                if (attempts < 3) {
                    cout << "password input error. Please re-enter again: ";
                } else {
                    cout << "password input error. Please try after a while.\n";
                }
            }
        }
    }

    void display() const {
        cout << "name: " << name << endl;
        cout << "pass: " << string(password.size(), '*') << endl;
        cout << "email: " << email << endl;
    }

private:
    string name;
    string password;
    string email;

    bool is_valid_email(const string& email) const {
        auto pos = email.find("@");
        return pos != string::npos && pos != 0 && pos != email.size() - 1;
    }
};

 

编译结果

 

实验任务6

代码

6 25.cpp

 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 }

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 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 }

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 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_ _

date.cpp

 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 }

date.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     void show() const;
16     int distance(const Date & date )const{
17         return totalDays - date.totalDays;
18     }
19 };

 

编译结果

 

posted @ 2024-11-05 03:19  starming  阅读(16)  评论(0编辑  收藏  举报