首页 > 编程语言 >实验3 类和对象_基础编程2

实验3 类和对象_基础编程2

时间:2024-11-08 21:40:52浏览次数:1  
标签:std const string 对象 编程 int 实验 include cout

试验任务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";
}

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

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

运行结果截图:

问题1:定义了botton和window类,使用了标准库的string和vector类,button类中使用了string类,window类中使用了botton类和vector类

问题2:不适合 有的是构造函数 有的是输出函数有变量 但是在输出类型void后加const 不会影响值的输出

问题3:输出*号将display输出的内容与其他内容隔断开

试验任务2:

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

运行结果截图:

问题1:第一行:初始化v1为5个42 第二行:v2复制v1 第三行:将v1的第一个42改成-999

问题2:第一行:初始化v1 相当于二维数组 第二行:v2为常量复制v1  第三行:将v1第一行中的最后一个改成-999

问题3:t1,t2分别赋值为v1,v2的第一行元素,输出这一行最后一个元素

问题4:深复制,有const接口

实验任务3:

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

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;

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

 

task3.cpp:

#include "vectorInt.hpp"
#include<iostream>

using std::cout;
using std::cin;

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

 

运行结果截图:

问题1:深复制

问题2:不能正常运行,报错:左操作数必须为左值;删除const后,运行结果正确

 问题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的矩阵,初始值为 value
    Matrix(int n);//构造函数,构造一个n*n的矩阵,初始值为 value
    Matrix(const Matrix& x);//复制构造函数,使用已有的矩阵x构造 
    ~Matrix();

    void set(const double* pvalue);//用pvalue指向的连续内存块数据按行为矩阵赋值
    void clear();//把矩阵对象的值置0

    const double& at(int i, int j)const;//返回矩阵对象索引(i,j)的元素const
    double& at(int i, int 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];
    for (int i = 0; i < n * m; ++i) {
        ptr[i] = 0.0;
    }
}

Matrix::Matrix(int n) :Matrix(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.0;
    }
}

const double& Matrix::at(int i, int j)const {
    assert(i >= 0 && i < lines && j >= 0 && j < cols);
    return ptr[i * cols + j];
}

double& Matrix::at(int i, int j) {
    assert(i >= 0 && i < lines && j >= 0 && j < cols);
    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) {
            cout << at(i, j) << " ";
        }
        cout << endl;
    }
}

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×m
    m1.set(x);          // 用一维数组x的值按行为矩阵m1赋值

    Matrix m2(m, n);    // 创建矩阵对象m1, 大小m×n
    m2.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();
}

运行结果截图:

 

实验任务5:

user.hpp

#pragma once

#include <iostream>
#include <string>

class User {
public:
    User(const std::string& username, const std::string& password = "", const std::string& email = "");

    void set_email();
    void change_password();
    void display() const;
    
private:
    std::string username_;
    std::string password_;
    std::string email_;
};

// 构造函数实现
User::User(const std::string& username, const std::string& password, const std::string& email)
    : username_(username), password_(password), email_(email) {}

void User::set_email() {
    std::string input_email;
    bool has_at_symbol = false;
    do {
        std::cout << "Enter email for " << username_ << ": ";
        std::cin >> input_email;
      
        for (char c : input_email) {
            if (c == '@') {
                has_at_symbol = true;
                break;
            }
        }
        if (!has_at_symbol) {
            std::cout << "无效的邮箱" << std::endl;
        }
    } while (!has_at_symbol);
    email_ = input_email;
}

void User::change_password() {
    std::string old_password;
    int attempts = 0;
    while (attempts < 3) {
        std::cout << "输入旧密码: " << username_ << ": ";
        std::cin >> old_password;
        if (old_password == password_) {
            std::string new_password;
            std::cout << "输入新密码: " << username_ << ": ";
            std::cin >> new_password;
            password_ = new_password;
            break;
        }
        else {
            attempts++;
            std::cout << "旧密码错误 " << 3 - attempts << std::endl;
        }
    }
    if (attempts == 3) {
        std::cout << "错误多次,稍后再试" << std::endl;
    }
}

void User::display() const {
    std::string password_display(password_.length(), '*');
    std::cout << "Username: " << username_ << ", Password: " << password_display << ", Email: " << email_;
}

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", "[email protected]");
    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();
}

运行结果截图:

试验任务6:

 account.h:

//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;//所有账户的总金额
             //记录一笔账,date为日期,amount为金额,desc为说明
        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);//结算利息,每年1月1日调用一次该函数
        void settle(const Date & date);
        //显示账户信息
        void show() const;
};
#endif //__ACCOUNT_H__#pragma once

 

date.h:

 //date.h
 #ifndef __DATE_H__
#define __DATE_H__
 class Date {//日期类
private:
         int year; //年
         int month;//月
         int day;//日
         int totalDays;//该日期是从公元元年1月1日开始的第几天
 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__

 

account.cpp:

//account.cpp
#include "account.h"
#include <cmath>
#include <iostream>
using namespace std;
double SavingsAccount::total = 0;
//SavingsAccount类相关成员函数的实现
 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");
    else
        record(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: " << id << "\tBalance: " << balance;
}

 

date.cpp:

//date.cpp
#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;
namespace {
    //namespace使下面的定义只在当前文件中有效
        const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 356 };
}
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;
    else return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
}
void Date::show() const {
    cout << getYear() << "-" << getMonth() << "-" << getDay();
}

 

task6.cpp:

//6.25.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)
     };
    //几笔账目
        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 < sizeof(accounts) / sizeof(SavingsAccount); i++) {
        accounts[i].settle(Date(2009, 1, 1));
        accounts[i].show();
        cout << endl;
    }
    cout << "Total: " << SavingsAccount::getTotal() << endl;
    return 0;
}

 

标签:std,const,string,对象,编程,int,实验,include,cout
From: https://www.cnblogs.com/pure-w/p/18525797

相关文章

  • 看一遍就会用——面向对象:类和对象,实例属性,实例方法,字符串表示
    python面向对象1.类和对象2.实例属性3.实例方法4.字符串表示1.__str__方法2.__repr__方法1.类和对象在Python中,类和对象是面向对象编程(OOP)的核心概念。类(Class)是创建对象的蓝图或模板,它定义了对象将拥有的属性和方法。对象(Object)则是根据类创建的具体实例,它包含了类......
  • 前端入门一之JS对象、字符串对象、数组对象、Data()对象等
    前言JS是前端三件套之一,也是核心,本人将会更新JS基础、JS对象、DOM、BOM、ES6等知识点,这篇是JS常用的内置对象;这篇文章是本人大一学习前端的笔记;欢迎点赞+收藏+关注,本人将会持续更新。文章目录目录总览1、对象1.1、创建对象(object)利用字面量创建对象对象的调用变量......
  • 实验3 类和对象_基础编程2
    实验任务11#pragmaonce23#include<iostream>4#include<string>56usingstd::string;7usingstd::cout;89//按钮类10classButton{11public:12Button(conststring&text);13stringget_label()const;14voi......
  • 希冀 操作系统 实验四 段式存储管理
    申请进程apply()函数完成了新开进程的功能,同时还记录了该进程需要的内存空间段数和每段的具体大小,你需要补全该函数。补全的代码为:voidapply(){printf("请输入进程的名字:");scanf("%s",duanbiaos[duanbiaonum].processname);printf("请输入该进程的段数:");......
  • 天天学编程Day10
    今日两道编程题LCR140. 训练计划IIclassSolution{public:ListNode*trainingPlan(ListNode*head,intcnt){//我选择使用双指针方法定义两个位置在头结点的指针//先让快指针先走cnt个位置然后让两个指针同时走//当快指针走到空节......
  • Cursor:编程软件中的璀璨明珠,解锁高效开发新姿势
    在编程领域,有一款备受瞩目的软件——Cursor。它为开发者们带来了全新的编程体验,无论是新手还是经验丰富的程序员都值得关注。本文将探讨Cursor的功能、特点以及它如何助力开发者提升编程效率。(无广)一、强大的功能特性(一)智能代码补全Cursor的代码补全功能堪称一绝。它不像......
  • C++ 函数对象、函数指针与Lambda表达式
    C++函数对象、函数指针与Lambda表达式函数指针函数指针(FunctionPointer)是指向函数的指针变量。它可以存储函数的地址,并通过该指针变量来调用该函数。函数指针的声明使用指针符号,指向的类型为函数的返回类型和参数列表,如int(funcPtr)(int,int);。函数指针的值可以指向相同......
  • 20222311 2024-2025-1 《网络与系统攻防技术》实验四实验报告
    1.实验内容1.1恶意代码文件类型标识、脱壳与字符串提取对提供的rada恶意代码样本,进行文件类型识别,脱壳与字符串提取,以获得rada恶意代码的编写作者,具体操作如下:(1)使用文件格式和类型识别工具,给出rada恶意代码样本的文件格式、运行平台和加壳工具;(2)使用超级巡警脱壳机等脱壳软件,......
  • 实验三 类和对象_基础编程2
    实验任务1button.hpp 1#pragmaonce23#include<iostream>4#include<string>56usingstd::string;7usingstd::cout;89//按钮类10classButton{11public:12Button(conststring&text);13stringget_label()con......
  • 关于虚拟仿真云实验教学_解决方案及优势介绍!
    在科技飞速演进的潮流下,虚拟仿真技术正不断蓬勃发展,成为教育领域的一颗耀眼之星。作为创新的教育手段,虚拟仿真云教学正逐渐受到越来越多教育机构的高度重视与广泛应用。本文将为您详细探讨虚拟仿真云实验教学的解决方案及其所带来的多重优势。虚拟仿真云-教育培训解决方案虚拟......