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

1. 实验任务1
button.hpp
 1 #pragma once
 2 #include <iostream>
 3 #include <string>
 4 using std::string;
 5 using std::cout;
 6 // 按钮类
 7 class Button {
 8 public:
 9     Button(const string& text);
10     string get_label() const;
11     void click();
12 private:
13     string label;
14 };
15 Button::Button(const string& text) : label{ text } {
16 }
17 inline string Button::get_label() const {
18     return label;
19 }
20 void Button::click() {
21     cout << "Button '" << label << "' clicked\n";
22 }
View Code
window.hpp
 1 #pragma once
 2 #include "button.hpp"
 3 #include <vector>
 4 #include <iostream>
 5 using std::vector;
 6 using std::cout;
 7 using std::endl;
 8 // 窗口类
 9 class Window {
10 public:
11     Window(const string& win_title);
12     void display() const;
13     void close();
14     void add_button(const string& label);
15 private:
16     string title;
17     vector<Button> buttons;
18 };
19 Window::Window(const string& win_title) : title{ win_title } {
20     buttons.push_back(Button("close"));
21 }
22 inline void Window::display() const {
23     string s(40, '*');
24     cout << s << endl;
25     cout << "window title: " << title << endl;
26     cout << "It has " << buttons.size() << " buttons: " << endl;
27     for (const auto& i : buttons)
28         cout << i.get_label() << " button" << endl;
29     cout << s << endl;
30 }
31 void Window::close() {
32     cout << "close window '" << title << "'" << endl;
33     buttons.at(0).click();
34 }
35 void Window::add_button(const string& label) {
36     buttons.push_back(Button(label));
37 }
View Code
task1.cpp
 1 #include "window.hpp"
 2 #include <iostream>
 3 using std::cout;
 4 using std::cin;
 5 void test() {
 6     Window w1("new window");
 7     w1.add_button("maximize");
 8     w1.display();
 9     w1.close();
10 }
11 int main() {
12     cout << "用组合类模拟简单GUI:\n";
13     test();
14 }
View Code

问题1:这个模拟简单GUI的示例代码中,自定义了几个类?使用到了标准库的哪几个类?,哪些
类和类之间存在组合关系?
自定义了2个类,用了vector和string类,vector和Button,Window和string,Button和string存在组合关系;
问题2:在自定义类Button和Window中,有些成员函数定义时加了const, 有些设置成了inline。如
果你是类的设计者,目前那些没有加const或没有设置成inline的,适合添加const,适合设置成
inline吗?陈述你的答案和理由。
不适合,剩下的需要修改元素或者执行操作并不简单;
问题3:类Window的定义中,有这样一行代码,其功能是?
初始化一个字符串s,s是40个*;
 
2. 实验任务2
task2.cpp
 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 void output1(const vector<int>& v) {
 6     for (auto& i : v)
 7         cout << i << ",";
 8     cout << "\b\b \n";
 9 }
10 
11 void output2(const vector<vector<int>>v) {
12     for (auto& i : v) {
13         for (auto& j : i) 
14             cout << j << ", ";
15         cout << "\b\b \n";
16     }
17 }
18 void test1() {
19     vector<int>v1(5, 42);
20     const vector<int>v2(v1);
21 
22     v1.at(0) = -999;
23     cout << "v1: "; output1(v1);
24     cout << "v2: "; output1(v2);
25     cout << "v1.at(0) = " << v1.at(0) << endl;
26     cout << "v2.at(0) = " << v2.at(0) << endl;
27 }
28 void test2() {
29     vector<vector<int>>v1{ {1,2,3},{4,5,6,7} };
30     const vector<vector<int>>v2(v1);
31 
32     v1.at(0).push_back(-999);
33     cout << "v1: \n"; output2(v1);
34     cout << "v2: \n"; output2(v2);
35 
36     vector<int>t1 = v1.at(0);
37     cout << t1.at(t1.size() - 1) << endl;
38     const vector<int> t2 = v2.at(0);
39     cout << t2.at(t2.size() - 1) << endl;
40 }
41 int main() {
42     cout << "测试1:\n";
43     test1();
44     cout << "\n测试2:\n";
45     test2();
46 }
View Code

 

问题1:测试1模块中,这三行代码的功能分别是?

初始化v1为42,42,42,42,42;用v1初始化v2;将v1的第一个数改成-999;
问题2:测试2模块中,这三行代码的功能分别是?
初始化v1为有三个vector类成员的vector型数组;用v1初始化v2;在v1的第一个vector成员中加入-999作为该成员的第四个成员;
问题3:测试2模块中,这四行代码的功能分别是?
用v1的第一个成员初始化t1;输出t1的最后一个成员;用v2的第一个成员初始化t2;输出t2的最后一个成员;
问题4:根据执行结果,反向分析、推断:
① 标准库模板类vector内部封装的复制构造函数,其实现机制是深复制还是浅复制?
深复制
② 模板类vector的接口at(), 是否至少需要提供一个const成员函数作为接口?
1个
 
3. 实验任务3
vectorInt.hpp
 1 #pragma once
 2 #include <iostream>
 3 #include <cassert>
 4 using std::cout;
 5 using std::endl;
 6 // 动态int数组对象类
 7 class vectorInt {
 8 public:
 9     vectorInt(int n);
10     vectorInt(int n, int value);
11     vectorInt(const vectorInt& vi);
12     ~vectorInt();
13 
14     int& at(int index);
15     const int& at(int index) const;
16 
17     vectorInt& assign(const vectorInt& v);
18     int get_size()const;
19 
20 private:
21     int size;
22     int* ptr;
23 };
24 vectorInt::vectorInt(int n) : size{ n }, ptr{ new int[size] } {
25 }
26 vectorInt::vectorInt(int n, int value) : size{ n }, ptr{ new int[size] } {
27     for (auto i = 0; i < size; ++i)
28         ptr[i] = value;
29 }
30 vectorInt::vectorInt(const vectorInt& vi) : size{ vi.size }, ptr{ new int[size] }
31 {
32     for (auto i = 0; i < size; ++i)
33         ptr[i] = vi.ptr[i];
34 }
35 vectorInt::~vectorInt() {
36     delete[] ptr;
37 }
38 const int& vectorInt::at(int index)const {
39     assert(index >= 0 && index < size);
40 
41     return ptr[index];
42 }
43 int& vectorInt::at(int index){
44     assert(index >= 0 && index < size);
45 
46     return ptr[index];
47 }
48 vectorInt& vectorInt::assign(const vectorInt& v) {
49     delete[]ptr;
50 
51     size = v.size;
52     ptr = new int[size];
53 
54     for (int i = 0; i < size; i++)
55         ptr[i] = v.ptr[i];
56 
57     return *this;
58 }
59 int vectorInt::get_size() const {
60     return size;
61 }
View Code
task3.cpp
 1 #include "vectorInt.hpp"
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 void output(const vectorInt &vi) {
 7     for (auto i = 0; i < vi.get_size(); ++i)
 8         cout << vi.at(i) << ", ";
 9     cout << "\b\b \n";
10 }
11 void test1() {
12     int n;
13         cout << "Enter n:";
14     cin >> n;
15 
16     vectorInt x1(n);
17     for (auto i = 0; i < n; i++)
18         x1.at(i) = i * i;
19     cout << "x1:"; output(x1);
20 
21     vectorInt x2(n, 42);
22     vectorInt x3(x2);
23     x2.at(0) = -999;
24     cout << "x2:"; output(x2);
25     cout << "x3:"; output(x3);
26 
27 }
28 void test2() {
29     const vectorInt x(5, 42);
30     vectorInt y(10, 0);
31 
32     cout << "y: "; output(y);
33     y.assign(x);
34     cout << "y: "; output(y);
35     cout << "x.at(0) = " << x.at(0) << endl;
36     cout << "y.at(0) = " << y.at(0) << endl;
37 }
38 int main() {
39     cout << "测试1: \n";
40     test1();
41     cout << "\n测试2: \n";
42     test2();
43 }
View Code

问题1:vectorInt类中,复制构造函数(line14)的实现,是深复制还是浅复制?
深复制;
问题2:vectorInt类中,这两个at()接口,如果返回值类型改成int而非int&(相应地,实现部分也同步修改),测试代码还能正确运行吗?
不能
如果把line18返回值类型前面的const掉,针对这个测试代码,是否有潜在安全隐患?尝试分析说明。
存在安全隐患,const int&表明这是一个返回值为const类型的引用,int值不可修改,去掉const后,引用值可能被修改,所以存在安全隐患。
问题3:vectorInt类中,assign()接口,返回值类型可以改成vectorInt吗?你的结论,及原因分析
可以,但不好。vectorInt表示这是一个类型的引用,而不是一个对象的拷贝,加上&后,提高了效率
 
4. 实验任务4
matrix.hpp
 1 #pragma once
 2 #include <iostream>
 3 #include <cassert>
 4 using std::cout;
 5 using std::endl;
 6 // 类Matrix的声明
 7 class Matrix {
 8 public:
 9     Matrix(int n, int m); // 构造函数,构造一个n*m的矩阵, 初始值为value
10     Matrix(int n); // 构造函数,构造一个n*n的矩阵, 初始值为value
11     Matrix(const Matrix& x); // 复制构造函数, 使用已有的矩阵X构造
12     ~Matrix();
13     void set(const double* pvalue); // 用pvalue指向的连续内存块数据按行为矩阵赋值
14         void clear(); // 把矩阵对象的值置0
15     const double& at(int i, int j) const; // 返回矩阵对象索引(i,j)的元素const引用
16         double& at(int i, int j); // 返回矩阵对象索引(i,j)的元素引用
17     int get_lines() const; // 返回矩阵对象行数
18     int get_cols() const; // 返回矩阵对象列数
19     void display() const; // 按行显示矩阵对象元素值
20 private:
21     int lines; // 矩阵对象内元素行数
22     int cols; // 矩阵对象内元素列数
23     double* ptr;
24 };
25 // 类Matrix的实现:待补足
26 Matrix::Matrix(int n, int m) :lines{ n }, cols{ m } {
27     ptr = new double[n * m]();
28 }
29 Matrix::Matrix(int n) :Matrix(n, n){}
30 Matrix::Matrix(const Matrix& x) :lines{ x.lines }, cols{ x.cols }{
31     delete[] ptr;
32 
33     ptr = new double[lines * cols];
34     for (int i = 0; i < lines * cols; ++i)
35         ptr[i] = x.ptr[i];
36 }
37 Matrix::~Matrix() {
38     delete[] ptr;
39 }
40 void Matrix::set(const double* pvalue) {
41     for (int i = 0; i < lines; ++i) {
42         for (int j = 0; j < cols; j++) {
43             ptr[i * cols + j] = pvalue[i * cols + j];
44         }
45     }
46 }
47 void Matrix::clear() {
48     std::fill(ptr, ptr + lines * cols, 0);
49 }
50 const double& Matrix::at(int i, int j) const {
51     assert(i >= 0 && i < lines && j >= 0 && j < cols);
52     return ptr[i * cols + j];
53 }
54 double& Matrix::at(int i, int j) {
55     assert(i >= 0 && i < lines && j >= 0 && j < cols);
56     return ptr[i * cols + j];
57 }
58 int Matrix::get_lines() const {
59     return lines;
60 }
61 
62 int Matrix::get_cols() const {
63     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 << ptr[i * cols + j] << " ";
69         }
70         cout << endl;
71     }
72 }
View Code
task4.cpp
 1 #include "matrix.hpp"
 2 #include <iostream>
 3 #include <cassert>
 4 using std::cin;
 5 using std::cout;
 6 using std::endl;
 7 const int N = 1000;
 8 // 输出矩阵对象索引为index所在行的所有元素
 9 void output(const Matrix& m, int index) {
10     assert(index >= 0 && index < m.get_lines());
11     for (auto j = 0; j < m.get_cols(); ++j)
12         cout << m.at(index, j) << ", ";
13     cout << "\b\b \n";
14 }
15 void test1() {
16     double x[1000] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
17     int n, m;
18     cout << "Enter n and m: ";
19     cin >> n >> m;
20     Matrix m1(n, m); // 创建矩阵对象m1, 大小n×m
21     m1.set(x); // 用一维数组x的值按行为矩阵m1赋值
22     Matrix m2(m, n); // 创建矩阵对象m1, 大小m×n
23     m2.set(x); // 用一维数组x的值按行为矩阵m1赋值
24     Matrix m3(2); // 创建一个2×2矩阵对象
25     m3.set(x); // 用一维数组x的值按行为矩阵m4赋值
26     cout << "矩阵对象m1: \n"; m1.display(); cout << endl;
27     cout << "矩阵对象m2: \n"; m2.display(); cout << endl;
28     cout << "矩阵对象m3: \n"; m3.display(); cout << endl;
29 }
30 void test2() {
31     Matrix m1(2, 3);
32     m1.clear();
33     const Matrix m2(m1);
34     m1.at(0, 0) = -999;
35     cout << "m1.at(0, 0) = " << m1.at(0, 0) << endl;
36     cout << "m2.at(0, 0) = " << m2.at(0, 0) << endl;
37     cout << "矩阵对象m1第0行: "; output(m1, 0);
38     cout << "矩阵对象m2第0行: "; output(m2, 0);
39 }
40 int main() {
41     cout << "测试1: \n";
42     test1();
43     cout << "测试2: \n";
44     test2();
45 }
View Code

 

 

5. 实验任务5
user.hpp
 1 #pragma once
 2 #include<iostream>
 3 #include<string>
 4 #include<vector>
 5 
 6 using namespace std;
 7 class User {
 8 public:
 9     User(const string &name,const string &password = "123456",const string &email=""):name(name),password(password),email(email){}
10 
11     void set_email() {
12         int a = 0;
13         while (true) {
14             if (a == 0)
15                 cout << "Enter email address:";
16             else
17                 cout << "Please re_enter email:";
18             cin >> email;
19             a++;
20             if (email.find('@') != string::npos) {
21                 cout << "email is set successfully..." << endl;
22                 break;
23             }
24             else
25                 cout << "illegal email.";
26         }
27     }
28 
29 
30     void change_password() {
31         int n = 0;
32         string old_password;
33 
34         while (n < 3) {
35             if (n ==0)
36                 cout << "Enter old password:";
37             else
38                 cout << "Please re_enter again:";
39             cin >> old_password;
40 
41             if (old_password == password) {
42                 string new_password;
43                 cout << "Enter new password:";
44                 cin >> new_password;
45                 password = new_password;
46                 cout << "new password is set successfully..." << endl;
47                 break;
48             }
49             else {
50                 cout << "password input error. ";
51                 n++;
52             }
53         }
54         if(n==3)
55         cout << "Please try after a while." << endl;
56     }
57 
58     void display()const {
59         cout << "name:  " << name << endl;
60         cout << "pass:  " << std::string(password.length(), '*') << endl;
61         cout << "email: " << email << endl;
62     }
63 
64 
65 private:
66     string name;
67     string password;
68     string email;
69 };
View Code
task5.cpp
 1 #include "user.hpp"
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 using std::cin;
 6 using std::cout;
 7 using std::endl;
 8 using std::vector;
 9 using std::string;
10 void test() {
11     vector<User> user_lst;
12     User u1("Alice", "2024113", "Alice@hotmail.com");
13     user_lst.push_back(u1);
14     cout << endl;
15     User u2("Bob");
16     u2.set_email();
17     u2.change_password();
18     user_lst.push_back(u2);
19     cout << endl;
20     User u3("Hellen");
21     u3.set_email();
22     u3.change_password();
23     user_lst.push_back(u3);
24     cout << endl;
25     cout << "There are " << user_lst.size() << " users. they are: " << endl;
26     for (auto& i : user_lst) {
27         i.display();
28         cout << endl;
29     }
30 }
31 int main() {
32     test();
33 }
View Code

 

6. 实验任务6
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     }
16     void show() const;
17     int distance(const Date& date)const {
18         return totalDays - date.totalDays;
19     }
20 };
View Code

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

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

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

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

 

 

posted @ 2024-11-05 16:43  Mikuuuu  阅读(12)  评论(1编辑  收藏  举报