实验3 类和对象

news/2024/11/13 9:37:09/文章来源:https://www.cnblogs.com/phanoto/p/18536504

实验任务1:

button.hpp

#pragma once#include <iostream>
#include <string>using std::string;
using std::cout;// 按钮类
class Button {
public:Button(const string &text);string get_label() const;void click();private:string label;
};Button::Button(const string &text): label{text} {
}inline string Button::get_label() const {return label;
}void Button::click() {cout << "Button '" << label << "' clicked\n";
}
View Code

window.hpp

#pragma once
#include "button.hpp"
#include <vector>
#include <iostream>using std::vector;
using std::cout;
using std::endl;// 窗口类
class Window{
public:Window(const string &win_title);void display() const;void close();void add_button(const string &label);private:string title;vector<Button> buttons;
};Window::Window(const string &win_title): title{win_title} {buttons.push_back(Button("close"));
}inline void Window::display() const {string s(40, '*');cout << s << endl;cout << "window title: " << title << endl;cout << "It has " << buttons.size() << " buttons: " << endl;for(const auto &i: buttons)cout << i.get_label() << " button" << endl;cout << s << endl;
}void Window::close() {cout << "close window '" << title << "'" << endl;buttons.at(0).click();
}void Window::add_button(const string &label) {buttons.push_back(Button(label));
}
View Code

task1.cpp

#include "window.hpp"
#include <iostream>using std::cout;
using std::cin;void test() {Window w1("new window");w1.add_button("maximize");w1.display();w1.close();
}int main() {cout << "用组合类模拟简单GUI:\n";test();
}
View Code

 问题1:自定义了button类和window类;使用了标准库中的string、vector、iostream类;window类与button类存在组合关系

问题2:不适合, 因为它们被调用时候不会改变数据,不需要加const,而且被调用的次数不多,不需要加inline

问题3:定义一个字符串s,它由40个*组成

实验任务2:

 task2.cpp

#include <iostream>
#include <vector>using namespace std;void output1(const vector<int> &v) {for(auto &i: v)cout << i << ", ";cout << "\b\b \n";
}void output2(const vector<vector<int>> v) {for(auto &i: v) {for(auto &j: i)cout << j << ", ";cout << "\b\b \n";}
}void test1() {vector<int> v1(5, 42);const vector<int> v2(v1);v1.at(0) = -999;cout << "v1: ";  output1(v1);cout << "v2: ";  output1(v2);cout << "v1.at(0) = " << v1.at(0) << endl;cout << "v2.at(0) = " << v2.at(0) << endl;
}void test2() {vector<vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};const vector<vector<int>> v2(v1);v1.at(0).push_back(-999);cout << "v1: \n";  output2(v1);cout << "v2: \n";  output2(v2);vector<int> t1 = v1.at(0);cout << t1.at(t1.size()-1) << endl;const vector<int> t2 = v2.at(0);cout << t2.at(t2.size()-1) << endl;
}int main() {cout << "测试1:\n";test1();cout << "\n测试2:\n";test2();
}
View Code

 问题1:先创建了一个名为v1的vector,包含5跟都是42的元素,然后创建一个名为v2的vector,并用v1来将其初始化,最后将v1的第一个元素改成了-999.

问题2:先创建了一个名为v1的二维vector,然后创建了一个名为v2的二维vector,并用v1来初始化,且因为v2前的const所以v2的值不能改变,最后在v1中的第一个元素“1,2,3”后面添加了一个-999.

问题3:创建了一个名为t1的的vector,并用v1的第一个元素来将其初始化,然后输出t1的最后一个元素的值;创建了一个名为t2的vector,并用v2的第一个元素来将其初始化,然后输出t2的最后一个元素的值,并且因为t2前的const所以t2不能被修改

问题4:

1.深复制

2.需要

实验任务3:

vocterInt.hpp

#pragma once#include <iostream>
#include <cassert>using std::cout;
using std::endl;// 动态int数组对象类
class vectorInt{
public:vectorInt(int n);vectorInt(int n, int value);vectorInt(const vectorInt &vi);~vectorInt();int& at(int index);const int& at(int index) const;vectorInt& assign(const vectorInt &v);int get_size() const;private:int size;int *ptr;       // ptr指向包含size个int的数组
};vectorInt::vectorInt(int n): size{n}, ptr{new int[size]} {
}vectorInt::vectorInt(int n, int value): size{n}, ptr{new int[size]} {for(auto i = 0; i < size; ++i)ptr[i] = value;
}vectorInt::vectorInt(const vectorInt &vi): size{vi.size}, ptr{new int[size]} {for(auto i = 0; i < size; ++i)ptr[i] = vi.ptr[i];
}vectorInt::~vectorInt() {delete [] ptr;
}const int& vectorInt::at(int index) const {assert(index >= 0 && index < size);return ptr[index];
}int& vectorInt::at(int index) {assert(index >= 0 && index < size);return ptr[index];
}vectorInt& vectorInt::assign(const vectorInt &v) {  delete[] ptr;       // 释放对象中ptr原来指向的资源
size = v.size;ptr = new int[size];for(int i = 0; i < size; ++i)ptr[i] = v.ptr[i];return *this;
}int vectorInt::get_size() const {return size;
}
View Code

task3.cpp

#include "vectorInt.hpp"
#include <iostream>using std::cin;
using std::cout;void output(const vectorInt &vi) {for(auto i = 0; i < vi.get_size(); ++i)cout << vi.at(i) << ", ";cout << "\b\b \n";
}void test1() {int n;cout << "Enter n: ";cin >> n;vectorInt x1(n);for(auto i = 0; i < n; ++i)x1.at(i) = i*i;cout << "x1: ";  output(x1);vectorInt x2(n, 42);vectorInt x3(x2);x2.at(0) = -999;cout << "x2: ";  output(x2);cout << "x3: ";  output(x3);
}void test2() {const vectorInt  x(5, 42);vectorInt y(10, 0);cout << "y: ";  output(y);y.assign(x);cout << "y: ";  output(y);cout << "x.at(0) = " << x.at(0) << endl;cout << "y.at(0) = " << y.at(0) << endl;
}int main() {cout << "测试1: \n";test1();cout << "\n测试2: \n";test2();
}
View Code

 问题1:深复制

问题2:不能,因为int&存储的是一个int类型的数据的地址,允许修改元素值,而int存储的是int类型数据的副本,无法修改原来的元素值;存在安全隐患,因为可能会改变元素的值。

问题3:可以,不过会额外创建一个vectorInt,需要额外的空间。

实验任务4:

matrix.hpp
#pragma once#include <iostream>
#include <cassert>using std::cout;
using std::endl;// 类Matrix的声明
class Matrix {
public:Matrix(int n, int m);           // 构造函数,构造一个n*m的矩阵, 初始值为valueMatrix(int n);                  // 构造函数,构造一个n*n的矩阵, 初始值为valueMatrix(const Matrix &x);        // 复制构造函数, 使用已有的矩阵X构造~Matrix();void set(const double *pvalue);         // 用pvalue指向的连续内存块数据按行为矩阵赋值void clear();                           // 把矩阵对象的值置0const double& at(int i, int j) const;   // 返回矩阵对象索引(i,j)的元素const引用double& at(int i, int j);               // 返回矩阵对象索引(i,j)的元素引用int get_lines() const;                  // 返回矩阵对象行数int get_cols() const;                   // 返回矩阵对象列数void display() const;                    // 按行显示矩阵对象元素值private:int lines;      // 矩阵对象内元素行数int cols;       // 矩阵对象内元素列数double *ptr;
};Matrix::Matrix(int n,int m):lines{n},cols{m}{ptr=new double[n*m];
}
Matrix::Matrix(int n){ptr=new double[n*n];
}Matrix::Matrix(const Matrix &x):lines{x.lines},cols{x.cols}{ptr=new double[lines*cols];for(int i=0;i<lines*cols;i++)ptr[i]=x.ptr[i];
}Matrix::~Matrix(){delete []ptr;
}void Matrix::set(const double* pvalue){for(int i=0;i<lines*cols;i++)ptr[i]=pvalue[i];
}void Matrix::clear(){for(int i=0;i<lines*cols;++i)ptr[i]=0;}const double& Matrix::at(int i,int j)const {return ptr[i*cols+j];
}
double& Matrix::at(int i,int j){return ptr[i*cols+j];
}
int Matrix::get_lines()const{return lines;
}
int Matrix::get_cols()const{return cols;
}
void Matrix::display()const{for(int i=0;i<lines*cols;i++){if((i+1)%cols!=0){cout<<ptr[i]<<" ,";}else{cout<<ptr[i]<<endl;}}
}
View Code

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×mm1.set(x);          // 用一维数组x的值按行为矩阵m1赋值
Matrix m2(m, n);    // 创建矩阵对象m1, 大小m×nm2.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();
}
View Code

 实验任务5:

 user.cpp

#pragma once#include<iostream>
#include<string>
#include<vector>using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;class User{public:User(string a, string b= "123456", string c= "");void set_email();void change_password();void display();private:string name,email,password;};User::User(string a, string b, string c):name {a}, password {b}, email {c} {
}void User::set_email() {cout << "Enter email address: ";int a=0;string newemail;while(!a) {cin >> newemail;for (char c: newemail) {if (c == '@') a=1;  }if(a==0)cout << "illegal email.Please re-enter email: "; else {email=newemail;cout << "email is set successfully..." << endl;}
}
}void User::change_password() {string t;cout << "Enter old password:" << endl;int c = 0;while(c < 3) {cin >> t;if(password==t) {cout << "Enter new password:" << endl;cin >> password;cout << "new password is set successfully...";break;} else {cout << "password input error. Please re-enter angain:" << endl;cin.clear();}++c;}if(c == 3) {cout << "password input error. Please try after a while.";} 
}void User::display() {cout << "name: " << name << endl;cout << "pass: ";for(int i = 0; i < password.size(); i++) {cout << "*";}cout << endl;cout << "eamil: " << email << endl;
}
View Code

task5.cpp

#include "user.hpp"
#include <iostream>
#include <vector>
#include <string>using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;void test() {vector<User> user_lst;User u1("Alice", "2024113", "Alice@hotmail.com");user_lst.push_back(u1);cout << endl;User u2("Bob");u2.set_email();u2.change_password();user_lst.push_back(u2);cout << endl;User u3("Hellen");u3.set_email();u3.change_password();user_lst.push_back(u3);cout << endl;cout << "There are " << user_lst.size() << " users. they are: " << endl;for(auto &i: user_lst) {i.display();cout << endl;}
}int main() {test();
}
View Code

 

 实验任务6:

date.h

#ifndef __DATE_H__
#define __DATE_H__
class Date {private:int year,month,day,totalDays;public:Date(int year,int month,int day);int getYear()const {return year;}int getMonth()const {return month;}int getDay() const {return day;}int getMaxDay() const;bool isLeapYear()const {return year%4==0 && year%100!=0 ||year%400==0;}void show()const;int distance(const Date &date)const {return totalDays-date.totalDays;}};
#endif / / _DATE_H__
View Code

date.cpp

#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;
namespace {const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}
Date::Date(int year, int month, int day) : year(year), month(month), day(day) {if (day <= 0 || day > getMaxDay()) {cout << "Invalid date:";show();cout << endl;exit(1);}int years = year - 1;totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;if (isLeapYear() && month > 2) totalDays++;
}
int Date::getMaxDay()const {if (isLeapYear() && month == 2)return 29;elsereturn DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
}
void Date::show() const {cout << getYear() << " - " << getMonth() << " - " << getDay();
}
View Code

 account.h

#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include "date.h"
#include <string>
class SavingsAccount {private:std::string id;double balance,rate,accumulation;Date lastDate;static double total;void record(const Date& date, double amount, const std::string& desc);void error(const std::string& msg) const;double accumulate(const Date& date) const {return accumulation + balance * date.distance(lastDate);}public:SavingsAccount(const Date& date, const std::string& id, double rate);const std::string& getId() const {return id;}double getBalance() const {return balance;}double getRate() const {return rate;}static double getTotal() {return total;}void deposit(const Date& date, double amount, const std::string& desc);void withdraw(const Date& date, double amount, const std::string& desc);void settle(const Date& date);void show() const;
};
#endif
View Code

account.cpp

#include "account.h"
#include <cmath>
#include <iostream>
using namespace std;
double SavingsAccount::total = 0;
SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {date.show();cout << "\t#" << id << "created" << endl;
}
void SavingsAccount::record(const Date& date, double amount, const string& desc) {accumulation = accumulate(date);lastDate = date;amount = floor(amount * 100 + 0.5) / 100;balance += amount;total += amount;date.show();cout << "t\#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}
void SavingsAccount::error(const string& msg) const {cout << "Error(# " << id << " ):" << msg << endl;
}
void SavingsAccount::deposit(const Date & date, double amount, const string & desc) {record(date, amount, desc);
}
void SavingsAccount::withdraw(const Date & date, double amount, const string& desc) {if (amount > getBalance())error("not enough money");elserecord(date, -amount, desc);
}
void SavingsAccount::settle(const Date& date) {double interest = accumulate(date) * rate//计算年息/ date.distance(Date(date.getYear() - 1, 1, 1));if (interest != 0)record(date, interest, "interest");accumulation = 0;
}
void SavingsAccount::show() const {cout << id << "\tBalance:" << balance;
}
View Code

task6.cpp

#include "account.h"
#include <iostream>
using namespace std;
int main() {//起始日期Date date(2008, 11, 1);//建立几个账户SavingsAccount accounts[] = {SavingsAccount(date,"03755217",0.015),SavingsAccount(date, "02342342", 0.015)};const int n = sizeof(accounts) / sizeof(SavingsAccount); //账户总数
accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");cout << endl;for (int i = 0; i < n; i++) {accounts[i].settle(Date(2009, 1, 1));accounts[i].show();cout << endl;}cout << "Total: " << SavingsAccount::getTotal() << endl;return 0;
}
View Code

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/830610.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【LaTex 2024软件下载与安装教程】

1、安装包 Latex2024: 链接:https://pan.quark.cn/s/1dad34ca4d8f 提取码:5bja 2、安装教程 1) 双击压缩包内intall-tl-windows.bat安装,弹窗安装对话框2) 自动弹出安装窗口,如果弹出以下窗口说明文件夹目录太长或者有中文,建议放磁盘根目录;如果没有弹出…

实现qt 窗口无边框拖拽

无边框拖拽是参考Qt实战6.万能的无边框窗口(FramelessWindow) - Qt小罗 - 博客园的文章,对其代码进行修改而来。 本篇一共会提供本人写的无边框的代码以及Qt实战6.万能的无边框窗口(FramelessWindow) - Qt小罗 - 博客园里面的完整代码供大家参考. 代码使用的话,我是直接让…

20222411 2024-2025-1 《网络与系统攻防技术》实验四实验报告

1.实验内容 1.1实践内容 一、恶意代码文件类型标识、脱壳与字符串提取 对提供的rada恶意代码样本,进行文件类型识别,脱壳与字符串提取,以获得rada恶意代码的编写作者,具体操作如下: (1)使用文件格式和类型识别工具,给出rada恶意代码样本的文件格式、运行平台和加壳工具…

第六次高级语言程序设计作业

这个作业属于哪个课程:https://edu.cnblogs.com/campus/fzu/2024C/ 这个作业要求在哪里: https://edu.cnblogs.com/campus/fzu/2024C/homework/13303 学号:102400110 姓名:阿卜杜拉阿布力克木 123456789101112这次作业难度还是很高我会继续努力!

水体颜色智能识别系统

水体颜色智能识别系统基于AI人工智能机器视觉分析识别技术,水体颜色智能识别系统通过现场监控摄像头,实现对河道、湖面及排水口水体颜色的智能检测与识别。这一系统能够代替人眼,对水体颜色进行24小时不间断的监测,有效克服了传统人工巡检的局限性,提高了监测的效率和准确…

仪表图像识别算法

仪表图像识别算法基于AI的机器视觉分析识别技术,通过训练深度学习模型,使得摄像头能够像人一样“看”懂仪表盘上的数据。这些现场监控摄像头能够实时捕捉仪表盘的图像,利用AI算法自动分析并识别出仪表的示数或开关状态。这种技术不仅能够在任何时间、任何地点进行自动读表,…

溺水识别摄像头防溺水系统

溺水识别摄像头防溺水系统采用了先进的AI算法,溺水识别摄像头防溺水系统能够准确识别出人体的姿态和动作。当有人员在泳池中挣扎、失去平衡或是长时间不动时,系统会立即判断这可能是一起溺水事件,并立即发出语音报警,提醒周围的人进行救援。同时,系统还会将提示消息推送给…

学期:2024-2025-1 学号:20241303 《计算机基础与程序设计》第七周学习总结

作业信息这个作业属于哪个课程 <班级的链接>(如2024-2025-1-计算机基础与程序设计)这个作业要求在哪里 <作业要求的链接>(如2024-2025-1计算机基础与程序设计第七周作业这个作业的目标 <写上具体方面>计算机科学概论(第七版)第8章 并完成云班课测试,《C…

2024-2025-1 20241327 《计算机基础与程序设计》第七周学习总结

作业信息 |2024-2025-1-计算机基础与程序设计)| |-- |- |2024-2025-1计算机基础与程序设计第七周作业)| |快速浏览一遍教材计算机科学概论(第七版),课本每章提出至少一个自己不懂的或最想解决的问题并在期末回答这些问题 |作业正文|https://www.cnblogs.com/shr060414/p/18…

PbootCMS 网站转移后无法打开报错提示“No input file specified”怎么办

问题:PbootCMS 网站转移后无法打开,提示“No input file specified”。 解决方案:删除 .user.ini 文件:检查根目录中是否存在 .user.ini 文件,如有则删除。 重启 Web 服务器:重启 Apache 或 Nginx 服务。 检查 PHP 配置:确保 cgi.fix_pathinfo 设置为 1。 检查 Nginx 配…

PbootCMS网站后台图片上传提示:“上传失败:存储目录创建失败!”

后台图片上传提示:“上传失败:存储目录创建失败!”问题描述:图片上传失败,提示存储目录创建失败。 解决方案:给根目录下的 static 文件夹增加写入权限,一般设置为 755 或 777,推荐 755 权限设置。chmod -R 755 /path/to/your/project/static扫码添加技术【解决问题】专…

PbootCMS基本调用标签大全

首页、栏目页、内页的标题、关键词、描述:首页:<title>{pboot:sitetitle}</title> 栏目页:<title>{pboot:if({sort:title}==){pboot:pagetitle}{else}{sort:title}{/pboot:if}</title> 内页:<title>{content:title}-{pboot:sitetitle}</t…