任务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 }View Code
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 }View Code
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 }View Code
运行结果
问题1:自定义了两个类:button和window;用到了标准库的string类和vector类;buttion类和vector类存在组合关系(vector<Button>)。
问题2:不适合;const修饰的函数不会改变对象的成员,inline适合修饰代码量小且调用次数多的函数。
问题3:美化运行窗口,增强终端可读性和易用性
任务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 }View Code
运行结果
问题1:为整型容器v1初始化5个值为42的元素;将v1的元素拷贝给v2;将v1中索引为0的元素设为-999。
问题2:定义一个容器v1,装着两个整型容器,并初始化这两个整行容器,使其元素分别为1,2,3和4,5,6,7;
定义一个const型的整数容器的容器,将v1的元素拷贝给它;
在v1中索引为0的整数容器中加入一个新元素-999。
问题3:定义一个整数容器t1,将v1中索引为0的容器的元素赋给它;
输出t1中最后一个元素并换行;
定义一个const型的整数容器t2,将v2中索引为0的容器的元素赋给它;
输出t2中最后一个元素并换行;
问题4:(1)深复制
(2)是,因为使用接口的对象可能为const类型。
任务3
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 }View Code
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 }View Code
运行结果
问题1:深复制
问题2:不能运行,报错如下:
因为只有返回引用类型的函数才能在调用时进行左值运算。
如果把line18返回值类型前面的const掉,针对这个测试代码,有潜在安全隐患。如果去掉const,at()返回的引用类型可能会被错误地改变。
问题3:当函数返回引用类型时,返回的是对象本身,没有复制的操作。如果改为vectorint,会导致返回值的拷贝,可能会降低性能。
任务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 // xxxView Code
matrix.cpp
1 #include "matrix.hpp" 2 #include<iostream> 3 #include <cstring> 4 using namespace std; 5 6 Matrix::Matrix(int n, int m):lines(n),cols(m) { 7 ptr = new double[n * m]; 8 } 9 10 Matrix::Matrix(int n) : Matrix(n, n) {} 11 12 Matrix::Matrix(const Matrix &x):lines(x.lines),cols(x.cols) { 13 ptr = new double[lines * cols]; 14 memcpy(ptr, x.ptr, sizeof(double) * lines * cols); 15 } 16 17 Matrix::~Matrix() { 18 delete[] ptr; 19 } 20 21 void Matrix::set(const double *pvalue) 22 { 23 memcpy(ptr, pvalue, sizeof(double) * lines * cols); 24 } 25 26 void Matrix::clear() 27 { 28 memset(ptr, 0, sizeof(double) * lines * cols); 29 } 30 31 const double& Matrix::at(int i, int j) const 32 { 33 return ptr[i * cols + j]; 34 } 35 36 double& Matrix::at(int i, int j) 37 { 38 return ptr[i * cols + j]; 39 } 40 41 int Matrix::get_lines() const 42 { 43 return lines; 44 } 45 46 int Matrix::get_cols() const 47 { 48 return cols; 49 } 50 51 void Matrix::display() const 52 { 53 for (int i = 0; i < lines; i++) 54 { 55 for (int j = 0; j < cols; j++) 56 { 57 std::cout << at(i, j) << " "; 58 } 59 std::cout << std::endl; 60 } 61 } 62 63View Code
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 }View Code
将test1中代码改为double x[1000] = {4, 5, 6, 1, 2, 3, 7, 8, 9};后运行结果为
任务5
user.hpp
1 #ifndef USER_HPP 2 #define USER_HPP 3 4 #include <iostream> 5 #include <vector> 6 #include <string> 7 8 class User { 9 private: 10 std::string name; 11 std::string password; 12 std::string email; 13 14 void input_email() { 15 while (true) { 16 std::cout << "请输入邮箱地址: "; 17 std::string input_email; 18 std::cin >> input_email; 19 if (input_email.find('@') != std::string::npos) { //如果输入的邮箱中有@ 20 email = input_email; 21 std::cout << "设置成功!\n"; 22 break; 23 } else { 24 std::cout << "邮箱格式不合法,请重新输入。\n"; 25 } 26 } 27 } 28 29 public: 30 // 只输入名字时,默认密码为“123456”,邮箱为空 31 User(const std::string& name) : name(name), password("123456"), email("") {} 32 33 // 自定义构造函数 34 User(const std::string& name, const std::string& password, const std::string& email) 35 : name(name), password(password), email(email) {} 36 37 void set_email() { //设置邮箱 38 input_email(); 39 } 40 41 void change_password() { //修改密码 42 std::string old_password; 43 int attempts = 0; //尝试次数(3) 44 while (attempts < 3) { 45 std::cout << "请输入旧密码: "; 46 std::cin >> old_password; 47 if (old_password == password) { //验证成功 48 std::cout << "请输入新密码: "; 49 std::string new_password; 50 std::cin >> new_password; 51 password = new_password; 52 std::cout << "密码修改成功。\n"; 53 return; 54 } else { //验证失败 55 std::cout << "旧密码错误,请重试。\n"; 56 attempts++; 57 } 58 } 59 std::cout << "多次输入错误,请稍后再试。\n"; 60 } 61 62 void display() const { //展示(密码隐藏) 63 std::cout << "用户名: " << name << "\n"; 64 std::cout << "密码: " << std::string(password.size(), '*') << "\n"; 65 std::cout << "邮箱: " << email << "\n"; 66 } 67 }; 68 69 #endif // USER_HPP #ifndef USER_HPP 70 #define USER_HPP 71 72 #include <iostream> 73 #include <vector> 74 #include <string> 75 76 class User { 77 private: 78 std::string name; 79 std::string password; 80 std::string email; 81 82 void input_email() { 83 while (true) { 84 std::cout << "请输入邮箱地址: "; 85 std::string input_email; 86 std::cin >> input_email; 87 if (input_email.find('@') != std::string::npos) { //如果输入的邮箱中有@ 88 email = input_email; 89 std::cout << "设置成功!\n"; 90 break; 91 } else { 92 std::cout << "邮箱格式不合法,请重新输入。\n"; 93 } 94 } 95 } 96 97 public: 98 // 只输入名字时,默认密码为“123456”,邮箱为空 99 User(const std::string& name) : name(name), password("123456"), email("") {} 100 101 // 自定义构造函数 102 User(const std::string& name, const std::string& password, const std::string& email) 103 : name(name), password(password), email(email) {} 104 105 void set_email() { //设置邮箱 106 input_email(); 107 } 108 109 void change_password() { //修改密码 110 std::string old_password; 111 int attempts = 0; //尝试次数(3) 112 while (attempts < 3) { 113 std::cout << "请输入旧密码: "; 114 std::cin >> old_password; 115 if (old_password == password) { //验证成功 116 std::cout << "请输入新密码: "; 117 std::string new_password; 118 std::cin >> new_password; 119 password = new_password; 120 std::cout << "密码修改成功。\n"; 121 return; 122 } else { //验证失败 123 std::cout << "旧密码错误,请重试。\n"; 124 attempts++; 125 } 126 } 127 std::cout << "多次输入错误,请稍后再试。\n"; 128 } 129 130 void display() const { //展示(密码隐藏) 131 std::cout << "用户名: " << name << "\n"; 132 std::cout << "密码: " << std::string(password.size(), '*') << "\n"; 133 std::cout << "邮箱: " << email << "\n"; 134 } 135 }; 136 137 #endif // USER_HPPView Code
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", "[email protected]"); 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 }View Code
运行结果
任务6
date.h
1 #ifndef __DATE_H__ 2 #define __DATE_H__ 3 class Date{ 4 private: 5 int year; 6 int month; 7 int day; 8 int totalDays; 9 public: 10 Date(int year,int month,int day); 11 int getYear() const {return year;} 12 int getMonth() const {return month;} 13 int getDay() const {return day;} 14 int getMaxDay() const; 15 bool isLeapYear() const { 16 return year%4==0 && year%100 !=0 ||year%400==0; 17 } 18 void show() const; 19 20 int distance(const Date& date) const { 21 return totalDays-date.totalDays; 22 } 23 }; 24 #endif //__DATE_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 20 int Date::getMaxDay() const { 21 if(isLeapYear()&&month==2) 22 return 29; 23 else 24 return DAYS_BEFORE_MONTH[month]-DAYS_BEFORE_MONTH[month-1]; 25 } 26 27 void Date::show() const { 28 cout<<getYear()<<"-"<<getMonth()<<"-"<<getDay(); 29 }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 public: 19 SavingsAccount(const Date &date,const std::string &id,double rate); 20 const std::string &getID() const {return id;} 21 double getBalance() const {return balance;} 22 double getRate() const {return rate;} 23 static double getTotal() {return total;} 24 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
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):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 string &msg) const { 20 cout<<"Error(#"<<id<<":"<<msg<<endl; 21 } 22 void SavingsAccount::deposit(const Date &date,double amount,const string &desc) { 23 record(date,amount,desc); 24 } 25 26 void SavingsAccount::withdraw(const Date &date,double amount,const string &desc) { 27 if(amount>getBalance()) 28 error("not enough money"); 29 else 30 record(date,-amount,desc); 31 } 32 33 void SavingsAccount::settle(const Date &date) { 34 double interest=accumulate(date) * rate/date.distance(Date(date.getYear()-1,1,1)); 35 if(interest!=0) 36 record(date,interest,"interest"); 37 accumulation=0; 38 } 39 void SavingsAccount::show() const{ 40 cout<<id<<"\tBalance:"<<balance; 41 }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 const int n=sizeof(accounts)/sizeof(SavingsAccount); 11 accounts[0].deposit(Date(2008,11,5),5000,"salary"); 12 accounts[1].deposit(Date(2008,11,25),10000,"sell stock 0323"); 13 accounts[0].deposit(Date(2008,12,5),5500,"salary"); 14 accounts[1].withdraw(Date(2008,12,20),4000,"buy a laptop"); 15 cout<<endl; 16 for(int i=0;i<n;i++){ 17 accounts[i].settle(Date(2009,1,1)); 18 accounts[i].show(); 19 cout<<endl; 20 } 21 cout<<"Total: "<<SavingsAccount::getTotal()<<endl; 22 return 0; 23 }View Code
运行结果
改进建议:
-
尽量使用
this
指针来表示当前对象,避免混淆。 -
在处理金钱方面,可以考虑引入一个更加稳健的金钱处理类,避免浮点数精度带来的问题。
-
可以考虑使用异常处理来处理错误,而不是简单地打印错误消息。
-
可以考虑在
show
函数中添加更多信息,如账户创建日期、利率等,提供更全面的账户状态信息。 -
如果函数不修改类的成员变量,应该将其声明为常量成员函数(使用
const
)。例如,getBalance()
、getId()
等函数如果只是读取值,则应声明为const
。 -
保持代码风格的一致性,比如在函数定义和参数之间的空白、括号的使用、控制流的结构等。