实验3 类和对象 基础编程

news/2024/12/25 2:31:55/文章来源:https://www.cnblogs.com/hinaou/p/18525723

实验一

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();
}

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";
}

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));
}

实验结果

问题一:自定义了一个窗口类和一个按钮类,运用了标准库的输入输出类,容器类,string类;容器类和输入输出类在自定义类有组合关系。

问题二:const 是只能调用而不能修改,inline是内联函数,可以对一些简单函数多次重复调用时使用。所以对于尚未设置的函数,观察是否值得保护还是会多次重复调用而来决定选择哪个

问题三:这行代码,可以输出一行40个*作为分割线

实验二

#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();
}

结果

问题一:第21行代码是输出5个42,第22行是为了为了后续输出v2和v1一致,第23行是为了改变v1中第一个为-999

问题二:第32行代码是输出v1为二维数组,第33行是为了后续v2和v1输出一致,第34行是为了加第一行最后一个为-999

问题三:39行是复制输出v1到t1上的,40行是输出t1上的东西,42行是将constv2赋值到t2,43行是输出t2

问题四:是深复制,不需要

实验三

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();
}

vectorInt.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;
}

实验结果

问题一:是浅复制

问题二:能正常运行,可能有风险,对返回的对象进行修改

问题三:返回引用类型的话可以提高效率,并且避免歧义

实验四

tesk.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();
}

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){lines=cols=n; ptr= new double[n*n];}
Matrix::Matrix(const Matrix &x){lines=x.lines;cols=x.cols;ptr=new double[x.lines,x.cols];for(int i=0;i<lines*cols;i++){*(ptr[i])=*(x.ptr[i]);} 
}   void Matrix:: clear(){*ptr=NULL;}Matrix::~Matrix(){delete[] ptr;}
void  Matrix:: set(const double *pvalue){for(int i=0;i<lines*cols;++i){*(ptr+i)=*(ptr+i);}     }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;i++){for(int j=0;j<cols;j++){std::cout<<*(ptr+i*cols+j)<<",";}std::cout<<"endl";}}

实验结果

实验五

test.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();
}

user.hpp

#pragma once#include <iostream>
#include <cassert>
#include<string>using std::cout;
using std::endl;
class User{private:string name;string password;string email;public:User (string a){name=a;password=123456;email=NULL;        }User(string a,string b,string c){name=a;password=b;email=c;}User::set_email(){string a;std::cout<<"Enter email adress";std::cout<<endl;std::cin>> a ;if(a.find('@')!=-1 ){std::cout<<"email is set successfully...";email=a;break;}else{std::cout<<"illegal email.please re-enter email";}}User::change_password(){string b;std::cout<<"Enter old password";std::cin>> b;if(b==password){break;}else{std::cout<<"password input error.Please re-enter again:    ";        std::cin>>b;}if(b==password){break;}else{std::cout<<"password input error.Please re-enter again:"    ;                  std::cin>>b;                                }if(b!=password){std::cout<<"password input error.Please try after a while";}User::display(){stirng c(password.size(),"*") std::cout<<"email:  "<<email<<endl;std::cout<<"password:   "<<c<<endl;std::cout<<"name:  "<<name<<endl;        }    };

实验结果:

实验六

date.h



#ifndef __DATE_H__
#define __DATE_H__
class Date {
private:
int year;
int month;
int day;
int 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.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();
}

account.h

#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include "date.h"
#include <string>
class SavingsAccount { 
private:std::string id;       double balance;       double rate;        Date lastDate;        double accumulation;    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 

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;
}

test.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;
}

实验结果

 

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

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

相关文章

别再被多线程搞晕了!一篇文章轻松搞懂 Linux 多线程同步!

别再被多线程搞晕了!一篇文章轻松搞懂 Linux 多线程同步!前言 大家有没有遇到过,代码跑着跑着,线程突然抢资源抢疯了?其实,这都是“多线程同步”在作怪。多线程同步是个老生常谈的话题,可每次真正要处理时还是让人头疼。这篇文章,带你从头到尾掌握 Linux 的多线程同步,…

『模拟赛』NOIP2024加赛2

『模拟赛记录』NOIP2024加赛2Rank 一直烂,什么时候触底反弹(A. 新的阶乘 赛时觉得线筛一遍同时统计每个质数的指数就做完了,然后本机怎么跑不进 1s,卡常卡了半个小时,最后没 T,但是 vector 炸了,70pts。 可以换思路考虑,赛时一直没转换过来。对于每个质数枚举其倍数统计…

矩阵求导 d(A*X)/dX

矩阵求导 d(A*X)/dX简单矩阵求导 $\frac{ \part (A \times X) }{ \part X }=A$。证明如下,自行体会。 感谢 https://www.cnblogs.com/sunny99/ sumoier对本文的帮助

学习笔记(二十六):资源分类与访问(Resources)

概述: 应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。 资源目录的示例如下所示, base目录、限定词目录、rawfile目录、resfile目录称为资源目录;element、media、profile称为资源组目录。resources |---base | |---element | | |---string.json | |…

java微服务的异常

1.依赖异常须知: 【 如果项目的结构是单个模块的,需要给每个单个模块添加起步依赖 spring-boot-starter-parent,指定版本 】 【 如果项目的结构是子父模块的,只需要给父模块添加起步依赖 spring-boot-starter-parent,指定版本,所有子模块引入父模块就行 】配置文件你指定…

C# WebSocket的简单使用【使用Fleck实现】

有bug,不推荐使用 有bug,不推荐使用 有bug,不推荐使用2.WebSocketHelper 新建 WebSocketHelper.csusing Fleck;namespace WebSocket {internal class WebSocketHelper{//客户端url以及其对应的Socket对象字典IDictionary<string, IWebSocketConnection> dic_Sockets =…

第三十五讲:为什么临时表可以重名?

创建临时表,一部分为了优化查询,join在临时表里查询出结果后导入到正常表中,他也支持多session的查询优化,更重要一点是在session会话关闭后,临时表会自动销毁。嗯就这样 另外分清他和内存表的区别 内存表一定是从memory引擎创建的,临时表可以由memory引擎创建第三十五讲…

如何理解shell命令 cd $(dirname $0)

如何理解shell命令 cd $(dirname $0)-CSDN博客

对C++程序使用输入输出重定向

一般来说,在Visual Studio使用文件重定向有三种方法: 方法一:通过命令行参数实现 项目→属性→配置属性→调试→命令参数然后就在这里加上你的命令行参数 比如我有这样一段程序: #include <iostream> #include <fstream> #include "Sales_item.h"int…

红米k70怎么设置「短信通知」在锁屏时隐藏内容,不锁屏时不隐藏内容

红米 K70 设置短信通知在锁屏时隐藏内容、不锁屏时不隐藏内容,可以按照以下步骤进行操作:打开手机设置:在主屏幕上找到并点击 “设置” 图标,进入手机设置页面。 进入通知与控制中心:在设置页面中,找到并点击 “通知与控制中心” 选项。 选择锁屏通知:在通知与控制中心页…

c语言中声明数组时, 元素个数必须使用常量表达式

001、[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c ## 测试程序 #include <stdio.h>int main(void) {int var1 = 5; // 初始化一个变量var1int array1[var1] = {3,5,8,4,9}; // 初始化数组return 0; } [root@PC1 test]# gcc test.c …

图的基本操作

目录1.图2.图的结构体定义3.图的初始化4.添加顶点、删除顶点4.1添加顶点4.2删除顶点5.添加边、删除边5.1添加边5.2删除边6.打印图7.main函数 在生命旅途中,我们就像是一个个节点,被无数看不见的边相连。每一次的相识与相离,都在这张巨大的网络图中留下独特的印记。 1.图 图(…