c++实验三
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 }
运行截图:
问题一:
自定义了两个类:Button类和Window类,使用了标准库中的string类以及vector类模板,Button类和Window类,Button类和string类,Window类和string类之间都存在组合关系,且Window类中使用了vector类模板
问题二:
Button类中的构造函数和click函数以及Window类中其余三个函数就应该设置成内联函数(直接将函数体放在类中),因为函数结构简单,调用次数可能频繁,语句少,在编译时就把函数体嵌入到主函数中,节省了时间开销
问题三:
创建一个string类对象s ,并且用40个连续的‘ * ’字符组成的串来初始化s
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) { //此处i依旧是指向一个容器,还要用j来指向i中每一个元素 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); //因为v2为const类型 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 }
问题一:
第一行代码:创建一个含有5个int类型元素的vector容器,且初始化每一个元素为42
第二行:复制构造函数,用vector容器v1来初始化v2,v2即为v1的一个副本(深复制)
第三行:v1.at(0) 表示返回vector容器v1 0号位置处元素的引用,代码表示将v1 0号位置出元素的值改为-999
问题二:
第一行:创建一个元素个数为2的容器v1,容器中的每个元素又是一个 包含int类型元素的vector容器,并且用{1,2,3}初始化v1中的第一个元素容器,用{4,5,6,7}初始化v1中的第二个元素容器
第二行:复制构造函数,用v1的值来创建一个const类型容器v2(深复制)
第三行:在v1容器的第一个元素容器中尾部增加一个元素-999
问题三:
第一行:用容器v1的第一个元素容器的值来初始化创建一个包含int类型元素的vector容器t1
第二行:输出t1容器中位置为3的元素的值
第三行:用容器v2的第一个元素容器的值来初始化创建一个const 型包含int类型元素的vector容器t2
第四行:输出t2容器中位置为2的元素的值
问题四:
1:深复制
2:不需要
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; //this现在指向正在初始化的对象,*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 32 void test2() { 33 const vectorInt x(5, 42); 34 vectorInt y(10, 0); 35 36 cout << "y: "; output(y); 37 y.assign(x); 38 cout << "y: "; output(y); 39 40 cout << "x.at(0) = " << x.at(0) << endl; 41 cout << "y.at(0) = " << y.at(0) << endl; 42 } 43 44 int main() { 45 cout << "测试1: \n"; 46 test1(); 47 48 cout << "\n测试2: \n"; 49 test2(); 50 }
运行截图:
问题1:
是深复制,因为重新用new函数动态分配了一块空间,地址不共享
问题2:
不是int &的话,那么数组的值就不能改变了,不能正常运行 line18行中的consts删去有隐患,虽然对象x是const类型,已经不能修改x中的数据成员,但只是指针和元素个数size不能改变,数组中的值依旧可以改变,为了确保数组中的值不能被改变,必须设为const int &类型
问题3:
可以,我改了一下,程序正常运行(感觉就是返回值为引用类型的话,就不用再调用一次复制构造函数了),返回值不是引用类型的话,就相当于assign之后又把那个初始化后的对象又用复制构造函数复制给了另一个新对象
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::Matrix(int n, int m) :lines(n), cols(m),ptr(new double[n*m]) { 35 36 } 37 38 Matrix::Matrix(int n) : lines(n), cols(n), ptr(new double[n * n]) { 39 40 } 41 42 Matrix::Matrix(const Matrix& x): lines(x.lines), cols(x.cols), ptr(new double[lines * cols]) { 43 for (auto i = 0; i < lines * cols; i++) 44 { 45 ptr[i] = x.ptr[i]; 46 47 } 48 } 49 50 Matrix::~Matrix() { 51 delete[] ptr; 52 } 53 54 void Matrix::set(const double* pvalue) 55 { 56 for (auto i = 0; i < lines * cols; i++) 57 { 58 ptr[i] = pvalue[i]; 59 } 60 61 } 62 63 void Matrix::clear() 64 { 65 for (auto i = 0; i < lines * cols; i++) 66 { 67 ptr[i] = 0; 68 } 69 } 70 71 const double& Matrix::at(int i, int j) const 72 { 73 assert(i >= 0 && i < lines&& j >= 0 && j < cols); 74 75 return ptr[i * lines + j]; 76 77 78 } 79 80 double& Matrix::at(int i, int j) 81 { 82 assert(i >= 0 && i < lines&& j >= 0 && j < cols); 83 84 return ptr[i * lines + j]; 85 86 } 87 88 89 int Matrix::get_lines() const 90 { 91 return lines; 92 } 93 94 int Matrix::get_cols() const 95 { 96 return cols; 97 } 98 99 void Matrix::display() const 100 { 101 for (auto i = 0; i < lines; i++) 102 { 103 for (auto j = 0; j < cols; j++) 104 { 105 cout << ptr[i * cols + j] << ", "; 106 } 107 cout << "\b\b \n"; 108 } 109 110 }
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 }
运行结果:
task5:
代码:
user.hpp:
1 #pragma once 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 6 using namespace std; 7 8 class User 9 { 10 private: 11 string name; 12 string password; 13 string email; 14 15 public: 16 User(string x1, string x2 = "123456", string x3 = "") :name(x1), password(x2), email(x3) { 17 18 } 19 20 void set_email(); 21 void change_password(); 22 void display(); 23 24 25 }; 26 27 28 29 void User::set_email() 30 { 31 cout << "Enter email address: "; 32 string newemail; 33 cin >> newemail; 34 35 36 auto pos = newemail.find("@"); 37 while (pos == newemail.npos) 38 { 39 cout << "illegal email.Please re-enter email: "; 40 cin >> newemail; 41 pos = newemail.find("@"); //这里不能再用auto pos=...了,难道你能用两次int定义pos吗 42 } 43 email = newemail; 44 cout << "email is set successfully..." << endl; 45 46 } 47 48 49 void User::change_password() 50 { 51 cout << "Enter old password: "; 52 string oldpassword; 53 int count = 0; 54 cin >> oldpassword; 55 while (oldpassword != password && count < 2) 56 { 57 58 cout << "password input error.Please re-enter again: "; 59 cin >> oldpassword; 60 count++; 61 62 } 63 if (count == 2 && oldpassword != password) 64 { 65 cout << "password input error.Please try after a while." << endl; 66 } 67 else 68 { 69 cout << "Enter new password: "; 70 string newpassword; 71 cin >> newpassword; 72 password = newpassword; 73 cout << "new password is set successfully..." << endl; 74 } 75 76 } 77 78 79 void User::display() 80 { 81 string x(password.size(), '*'); 82 cout << "name:\t" << name << endl; 83 cout << "pass:\t" << x << endl; 84 cout << "email:\t" << email << endl; 85 86 }
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 }
运行结果:
task6:
代码:
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 } 19 void show() const; 20 int distance(const Date& date)const { 21 return totalDays - date.totalDays; 22 23 } 24 25 }; 26 #endif
date.cpp:
1 #include"date.h" 2 #include<iostream> 3 #include<cstdlib> 4 using namespace std; 5 namespace { 6 const int DAYS_BEFIRE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304 ,334,365 }; 7 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 } 17 int years = year - 1; 18 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFIRE_MONTH[month - 1] + day; 19 if (isLeapYear() && month > 2) totalDays++; 20 21 } 22 int Date::getMaxDay()const { 23 if (isLeapYear() && month == 2) 24 return 29; 25 else return DAYS_BEFIRE_MONTH[month] - DAYS_BEFIRE_MONTH[month - 1]; 26 27 } 28 void Date::show()const { 29 cout << getYear() << "-" << getMonth() << "-" << getDay(); 30 31 }
account.h:
1 #ifndef __ACCOUNT_H__ 2 #define __ACCOUNT_H__ 3 #include"date.h" 4 #include<string> 5 using namespace std; 6 class SavingsAccount { 7 private: 8 string id; 9 double balance; 10 double rate; 11 Date lastDate; 12 double accumulation; 13 static double total; 14 void record(const Date& date, double amount, const string& desc); 15 void error(const string& msg) const; 16 double accumulate(const Date& date)const { 17 return accumulation + balance * date.distance(lastDate); 18 19 } 20 public: 21 SavingsAccount(const Date& date, const string& id, double rate); 22 const string& getId()const { return id; } 23 double getBalance()const { return balance; } 24 double getRate()const { return rate; } 25 static double getTotal() { return total; } 26 void deposit(const Date& date, double amount, const string& desc); 27 void withdraw(const Date& date, double amount, const string& desc); 28 void settle(const Date& date); 29 void show() const; 30 31 }; 32 #endif
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 void SavingsAccount::record(const Date& date, double amount, const 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 string& msg) const { 21 cout << "Error(#" << id << "):" << msg << endl; 22 } 23 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 24 record(date, amount, desc); 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 void SavingsAccount::settle(const Date& date) { 33 double interest = accumulate(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1)); 34 if (interest != 0) record(date, interest, "interest"); 35 accumulation = 0; 36 } 37 void SavingsAccount::show()const { 38 cout << id << "\tBalance: " << balance; 39 }
task6.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 }
运行结果:
改进:
之前账户是用一个整数来表示,现在是用串来表示,并且把账户放在一个数组中,这样输出和变更时就不用一个个操作了,设置了Date类,其中存放年月日,表示日期时更加直观,相对天数也可以由公式得到,并且设置了报错函数
优化:
数据都是事先设置好的,但银行都是由用户自己输入的数据,可以改进一下,并且还应该设置密码,例如task5中
实验总结:
之前对vector和string用法都不太清楚,这次因为实验的缘故,特意通过csdn了解了他们的基础用法
我感觉最有意思的还是task5,让我部分了解了密码设置,比如通过string中的find函数来查找@这个字符,找不到就返回一个常量值string.npos而不是索引值
task6又让我对银行账户有了进一步的认识,也让我了解了一些其他函数,比如下取整函数floor,同时让我知道如何取两位小数(四舍五入)等等