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

task1:

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 // 窗口类
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 }

 

 

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 }

task1运行测试结果截图:

 

问题1:定义了Button和Window两个类,使用了标准库的string和vector两个类

Button和string之间组合,Window和vector、Button组合。

问题2:不适合,添加const或inline是将类的元素固定或者内联,改变其他成员函数类型会导致程序出错。

问题3:将s数组前40个单元存放“*”。

 

task2:

 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 }

task2运行测试结果截图:

问题1:

  vector<int> v1(5, 42);   创建了一个名为 v1 的动态数组其初始化一个可以容纳 5 个元素的向量,并    且所有初始元素值都设置为 42。

  vector<int> v2(v1);  将v1动态数组内容复制到v2动态数组中。

  v1.at(0) = -999;  将v1中第一个数赋值为-999。

问题2:

  vector<vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};  定义了一个二维动态数组vector<vector<int>> v1,它包含两个一维向量,每个一维向量分别存储整数。第一个向量{1, 2, 3}有三个元素,第二个向量{4, 5, 6, 7}有四个元素。  
  vector<vector<int>> v2(v1);将v1动态数组内容复制到v2动态数组中。
  v1.at(0).push_back(-999);将v1动态数组第一个元素后插入-999。

问题3:

  vector<int> t1 = v1.at(0);将v1向量中索引为0的元素赋值给t1
  cout << t1.at(t1.size()-1) << endl;输出t1向量的最后一个元素
  const vector<int> t2 = v2.at(0);将v2向量中索引为0的子向量赋值给t2
  cout << t2.at(t2.size()-1) << endl;输出t2向量的最后一个元素

问题4:

标准库模板类vector内部封装的复制构造函数,其实现机制是深复制还是浅复制?
深复制。
模板类vector的接口at(), 是否至少需要提供一个const成员函数作为接口?
是。
 
task3:
vectorInt.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 }

 

task3运行测试结果截图:
 
问题1:vectorInt类中,复制构造函数(line14)的实现,是深复制还是浅复制?
  深复制
问题2:vectorInt类中,这两个at()接口,如果返回值类型改成int而非int&(相应地,实现部分也
同步修改),测试代码还能正确运行吗?如果把line18返回值类型前面的const掉,针对这个测试
代码,是否有潜在安全隐患?尝试分析说明。
  不能正常运行,存在隐患
问题3:vectorInt类中,assign()接口,返回值类型可以改成vectorInt吗?你的结论,及,原因分
析。
  可以,代码可运行,但是会占用额外内存。
 
task4:
matrix.hpp:
 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) : lines(n), cols(m), ptr(new double[lines * cols]) {
36     clear();
37 }
38 
39 Matrix::Matrix(int n) : Matrix(n, n) {}
40 
41 Matrix::Matrix(const Matrix& x) : lines(x.lines), cols(x.cols), ptr(new double[lines * cols]) {
42     for (int i = 0; i < lines * cols; ++i) {
43         ptr[i] = x.ptr[i];
44     }
45 }
46 
47 Matrix::~Matrix() {
48     delete[] ptr;
49 }
50 
51 void Matrix::set(const double* pvalue) {
52     for (int i = 0; i < lines * cols; ++i) {
53         ptr[i] = pvalue[i];
54     }
55 }
56 
57 void Matrix::clear() {
58     for (int i = 0; i < lines * cols; ++i) {
59         ptr[i] = 0;
60     }
61 }
62 
63 const double& Matrix::at(int i, int j) const {
64     assert(i >= 0 && i < lines && j >= 0 && j < cols);
65     return ptr[i * cols + j];
66 }
67 
68 double& Matrix::at(int i, int j) {
69     assert(i >= 0 && i < lines && j >= 0 && j < cols);
70     return ptr[i * cols + j];
71 }
72 
73 int Matrix::get_lines() const {
74     return lines;
75 }
76 
77 int Matrix::get_cols() const {
78     return cols;
79 }
80 
81 void Matrix::display() const {
82     for (int i = 0; i < lines; ++i) {
83         for (int j = 0; j < cols; ++j) {
84             cout << at(i, j) << " ";
85         }
86         cout << endl;
87     }
88 }

 

task4.cpp
#include "matrix.hpp"
#include <iostream>
#include <cassert>

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


const int N = 1000;

// 输出矩阵对象索引为index所在行的所有元素
void output(const Matrix &m, int index) {
    assert(index >= 0 && index < m.get_lines());

    for(auto j = 0; j < m.get_cols(); ++j)
        cout << m.at(index, j) << ", ";
    cout << "\b\b \n";
}


void test1() {
    double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int n, m;
    cout << "Enter n and m: ";
    cin >> n >> m;

    Matrix m1(n, m);    // 创建矩阵对象m1, 大小n×m
    m1.set(x);          // 用一维数组x的值按行为矩阵m1赋值

    Matrix m2(m, n);    // 创建矩阵对象m1, 大小m×n
    m2.set(x);          // 用一维数组x的值按行为矩阵m1赋值

    Matrix m3(2);       // 创建一个2×2矩阵对象
    m3.set(x);          // 用一维数组x的值按行为矩阵m4赋值

    cout << "矩阵对象m1: \n";   m1.display();  cout << endl;
    cout << "矩阵对象m2: \n";   m2.display();  cout << endl;
    cout << "矩阵对象m3: \n";   m3.display();  cout << endl;
}

void test2() {
    Matrix m1(2, 3);
    m1.clear();
    
    const Matrix m2(m1);
    m1.at(0, 0) = -999;

    cout << "m1.at(0, 0) = " << m1.at(0, 0) << endl;
    cout << "m2.at(0, 0) = " << m2.at(0, 0) << endl;
    cout << "矩阵对象m1第0行: "; output(m1, 0);
    cout << "矩阵对象m2第0行: "; output(m2, 0);
}

int main() {
    cout << "测试1: \n";
    test1();

    cout << "测试2: \n";
    test2();
}

 

task4运行测试结果截图:

task5:

 user.hpp:

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 class User {
 7 private:
 8     std::string name;
 9     std::string password;
10     std::string email;
11 
12 public:
13 
14     User(const std::string& username, const std::string& userpassword = "123456", const std::string& useremail = "")
15         : name(username), password(userpassword), email(useremail) {}
16 
17 
18     void set_email() {
19         std::string input;
20         while (true) {
21             std::cout << "Enter email address: ";
22             std::cin >> input;
23             if (input.find('@') != std::string::npos) {
24                 email = input;
25                 std::cout << "email is set successfully..." << std::endl;
26                 break;
27             } else {
28                 std::cout << "illegal email, please re-enter email:" ;
29                 std::cin>>email;
30                 std::cout;
31             }
32         }
33     }
34 
35 
36     void change_password() {
37         std::string old_password;
38         int attempts = 1;
39         while (attempts < 3) {
40             std::cout << "Enter old password: ";
41             std::cin >> old_password;
42             if (old_password == password) {
43                 std::string new_password;
44                 std::cout << "Enter new password: ";
45                 std::cin >> new_password;
46                 password = new_password;
47                 std::cout << "new password is set successfully..." << std::endl;
48                 return;
49             } else {
50                 std::cout << "password input error.Please re-enter again:" ;
51                 attempts++;
52             }
53         }
54         std::cout << "password input error. Please try after a while." << std::endl;
55     }
56 
57 
58     void display() const {
59         std::cout << "name: " << name << std::endl;
60         std::cout << "password: ";
61         for (size_t i = 0; i < password.length(); ++i) {
62             std::cout << '*';
63         }
64         std::cout << std::endl;
65         std::cout << "email: " << email << std::endl;
66     }
67 };

 

task.cpp:

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

 

task5运行测试结果截图:

 

task6:

date.h:

 1 //date.h
 2 #ifndef __DATE_H__
 3 #define __DATE_H__
 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_H__

date.cpp:

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

account.h:

 1 //account.h
 2 #ifndef __ACCOUNT_H__
 3 #define __ACCOUNT_H__
 4 #include "date.h"
 5 #include <string>
 6 class SavingsAccount { //储蓄账户类
 7 private:
 8     std::string id;        //帐号
 9     double balance;        //余额
10     double rate;        //存款的年利率
11     Date lastDate;        //上次变更余额的时期
12     double accumulation;    //余额按日累加之和
13     static double total;    //所有账户的总金额
14     //记录一笔帐,date为日期,amount为金额,desc为说明
15     void record(const Date & date, double amount, const std::string & desc);
16     //报告错误信息
17     void error(const std::string & msg) const;
18     //获得到指定日期为止的存款金额按日累积值
19     double accumulate(const Date & date) const {
20         return accumulation + balance * date.distance(lastDate);
21     }
22 public:
23     //构造函数
24     SavingsAccount(const Date & date, const std::string & id, double rate);
25     const std::string & getId() const { return id; }
26     double getBalance() const { return balance; }
27     double getRate() const { return rate; }
28     static double getTotal() { return total; }
29     //存入现金
30     void deposit(const Date & date, double amount, const std::string & desc);
31     //取出现金
32     void withdraw(const Date & date, double amount, const std::string & desc);
33     //结算利息,每年1月1日调用一次该函数
34     void settle(const Date & date);
35     //显示账户信息
36     void show() const;
37 };
38 #endif //__ACCOUNT_H__

 

account.cpp:

 1 //account.cpp
 2 #include "account.h"
 3 #include <cmath>
 4 #include <iostream>
 5 using namespace std;
 6 double SavingsAccount::total = 0;
 7 //SavingsAccount类相关成员函数的实现
 8 SavingsAccount::SavingsAccount(const Date & date, const string & id, double rate)
 9     : id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
10     date.show();
11     cout << "\t#" << id << " created" << endl;
12 }
13 void SavingsAccount::record(const Date & date, double amount, const string & desc) {
14     accumulation = accumulate(date);
15     lastDate = date;
16     amount = floor(amount * 100 + 0.5) / 100;    //保留小数点后两位
17     balance += amount;
18     total += amount;
19     date.show();
20     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
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 void SavingsAccount::settle(const Date & date) {
35     double interest = accumulate(date) * rate    //计算年息
36         / date.distance(Date(date.getYear() - 1, 1, 1));
37     if (interest != 0)
38         record(date, interest, "interest");
39     accumulation = 0;
40 }
41 void SavingsAccount::show() const {
42     cout << id << "\tBalance: " << balance;
43 }

 

task6.cpp

 1 //6_25.cpp
 2 #include "account.h"
 3 #include <iostream>
 4 using namespace std;
 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 }

 

task6运行测试结果截图:

 

posted @ 2024-11-10 13:46  雪藏的熊  阅读(1)  评论(0编辑  收藏  举报