程序设计实验3
任务1
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 }
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 }
代码运行截图:
问题1:新定义了button和window两个类,使用了string和vector标准库中的函数,并且window定义在button的基础上
问题2:我认为有些函数没有必要添加const或者inline,例如void click();此函数只需简单输出,多此一举意义不大,并且此处变量没有进行初始化。
问题3:string s(40,“*”);的功能是一行元素全为“*”的字符串,在此代码中起到分隔页面的作用。
任务2
task2.cpp
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:line21作用是定义一个int类型容器,大小为5,容器元素为42. line22作用是在初始化v1的条件下进行复制。line24作用是将v1中下标为0的元素替换为-999.
问题2:line32作用是定义一个二维容器v1,并且给出第一行和第二行元素。line33作用是复制v1。line35作用是在v1的第0行末尾再添加一个元素-999.
问题3:line39作用是定义一个t1为v1的第0行,line40作用是输出t1末尾元素,line42作用是定义一个const容器t2为v2第0行,line43输出t2末尾元素。
问题4:(1)深复制 (2)需要
任务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 // 动态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 }
代码运行截图:
问题1:深复制
问题2:修改后会产生如下报错:// [Error] lvalue required as left operand of assignment//,程序无法正常运行,删除const后可能会导致数据泄露.
问题3:不可以,违背标准库设计,返回值类型被改变。
任务4
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[n * m]()) {} 36 37 Matrix::Matrix(int n) : lines(n), cols(n), ptr(new double[n * n]()) {} 38 39 Matrix::Matrix(const Matrix& x) : lines(x.lines), cols(x.cols), ptr(new double[lines * cols]()) { 40 for (int i = 0; i < lines * cols; i++) 41 ptr[i] = x.ptr[i]; 42 43 } 44 45 Matrix::~Matrix() { 46 delete[] ptr; 47 48 } 49 50 void Matrix::set(const double* pvalue) { 51 for (int i = 0; i < lines * cols; i++) 52 ptr[i] = pvalue[i]; 53 54 } 55 56 void Matrix::clear() { 57 for (int i = 0; i < lines * cols; i++) 58 ptr[i] = 0.0; 59 60 } 61 62 const double& Matrix::at(int i, int j) const 63 { 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 { 70 assert(i >= 0 && i < lines && j >= 0 && j < cols); 71 return ptr[i * cols + j]; 72 } 73 74 int Matrix::get_lines() const { 75 return lines; 76 } 77 78 int Matrix::get_cols() const { 79 return cols; 80 81 } 82 83 void Matrix::display() const { 84 for (int i = 0; i < lines; i++) { 85 for (int j = 0; j < cols; j++) { 86 cout << at(i, j) << " "; 87 88 } 89 cout << endl; 90 } 91 }
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] = {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 }
代码运行截图:
任务5
user.hpp
1 #pragma once 2 #include <iostream> 3 #include <string> 4 5 using namespace std; 6 7 class User 8 { 9 public: 10 User(string name, string password = "123456", string email = ""); 11 void set_email(); 12 void change_password(); 13 void display() const; 14 15 private: 16 string name; 17 string password; 18 string email; 19 }; 20 User::User(string name, string password, string email) : name{ name }, password{ password }, email{ email } {} 21 void User::set_email() 22 { 23 string input; 24 do 25 { 26 cout << "请输入邮箱: "; 27 getline(cin, input); 28 // 简单的邮箱合法性校验 29 if (input.find('@') != string::npos) 30 { 31 email = input; 32 } 33 else 34 { 35 cout << "非法邮箱,请输入包含@的邮箱。" << endl; 36 } 37 } while (input.find('@') == string::npos); 38 } 39 void User::change_password() 40 { 41 string old_password; 42 int attempts = 0; 43 while (attempts < 3) 44 { 45 cout << "请输入旧密码: "; 46 cin >> old_password; 47 if (old_password == password) 48 { 49 string new_password; 50 cout << "请输入新密码: "; 51 cin >> new_password; 52 password = new_password; 53 return; 54 } 55 else 56 { 57 cout << "密码错误。" << endl; 58 attempts++; 59 if (attempts == 3) 60 { 61 cout << "连续三次输入错误,稍后再试。" << endl; 62 } 63 } 64 } 65 } 66 void User::display() const 67 { 68 cout << "用户名: " << name << endl; 69 cout << "密码: " << string(password.length(), '*') << endl; 70 cout << "邮箱: " << email << endl; 71 }
task5.cpp
1 #include "user.hpp" 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string; 10 using std::vector; 11 12 void test() 13 { 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 { 35 i.display(); 36 cout << endl; 37 } 38 } 39 40 int main() 41 { 42 test(); 43 }
代码运行截图:
任务6
date.h
1 #pragma once 2 class Date { 3 private: 4 int year; int month; int day; int totalDays; 5 public: 6 Date(int year, int month, int day); 7 int getYear()const { return year; } 8 int getMonth()const { return month; } 9 int getDay()const { return day; } 10 int getMaxDay()const; 11 bool isLeapYear()const { 12 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 13 } 14 void show()const; 15 int distance(const Date& date)const { 16 return totalDays - date.totalDays; 17 } 18 };
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 }
account.h
1 #include"date.h" 2 #include<string> 3 class SavingsAccount { 4 private: 5 std::string id; 6 double balance; 7 double rate; 8 Date lastDate; 9 double accumulation; 10 static double total; 11 void record(const Date& date, double amount, const std::string& desc); 12 void error(const std::string& msg)const; 13 double accumulate(const Date& date)const { 14 return accumulation + balance * date.distance(lastDate); 15 } 16 public: 17 SavingsAccount(const Date& date, const std::string& id, double rate); 18 const std::string& getId()const { return id; } 19 double getBalance()const { return balance; } 20 double getRate()const { return rate; } 21 static double getTotal() { return total; } 22 void deposit(const Date& date, double amount, const std::string& desc); 23 void withdraw(const Date& date, double amount, const std::string& desc); 24 void settle(const Date& date); 25 void show()const; 26 };
account.cpp
1 #include"account.h" 2 #include<cmath> 3 #include<iostream> 4 using namespace std; 5 double SavingsAccount::total = 0; 6 7 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) { 8 date.show(); 9 cout << "\t#" << id << "created" << endl; 10 } 11 void SavingsAccount::record(const Date& date, double amount, const std::string& desc) { 12 accumulation = accumulate(date); 13 lastDate = date; 14 amount = floor(amount * 100 + 0.5) / 100; 15 balance += amount; 16 total += amount; 17 date.show(); 18 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 19 } 20 void SavingsAccount::error(const std::string& msg)const { 21 cout << "Error(#" << id << ");" << msg << endl; 22 } 23 void SavingsAccount::deposit(const Date& date, double amount, const std::string& desc) { 24 record(date, amount, desc); 25 } 26 void SavingsAccount::withdraw(const Date& date, double amount, const std::string& desc) { 27 if (amount > getBalance()) 28 { 29 error("not enough money"); 30 } 31 else 32 record(date, -amount, desc); 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 void SavingsAccount::show()const { 41 cout << id << "\tBalance:" << balance; 42 }
test.cpp
1 #include"account.h" 2 #include<iostream> 3 using namespace std; 4 int main() 5 { 6 Date date(2008, 11, 1); 7 SavingsAccount accounts[] = { 8 SavingsAccount(date,"03755217",0.015), 9 SavingsAccount(date,"02342342",0.015) 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 15 accounts[0].deposit(Date(2008, 12, 5), 5500, "salary"); 16 accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop"); 17 18 cout << endl; 19 for (int i = 0; i < n; i++) 20 { 21 accounts[i].settle(Date(2009, 1, 1)); 22 accounts[i].show(); 23 cout << endl; 24 } 25 cout << "Total:" << SavingsAccount::getTotal() << endl; 26 return 0; 27 }
代码运行截图: