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

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

时间:2024-11-04 22:58:05浏览次数:3  
标签:std const string 对象 编程 int 实验 vectorInt include

任务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

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

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

 

 运行结果:

 

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

问题2:剩下的函数多为执行输出操作,不会改变变量的值,所以没有必要使用const类型,在考虑到函数的编译效率时,可以将一些函数设为内联函数;

问题3:定义一个长度为48的类型的字符串,元素都为“*”;

 

 

任务2:

问题1:第一行定义了一个长度为5,元素都为42的vecto型类型字符串v1;第二行通过v1复制构造出了v2;第三行将v1的第一个元素的值改为-999;

问题2:第一行定义了二维向量并完成了赋值;第二行通过v1复制构造了v1;第三行在v1的第一个元素后插入了-999这个元素;

问题3:定义了v1,v2的第一个元素并输出最后一个元素

 问题4:是深复制。需要提供。

 

 

 

 

任务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;       // 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:不能正确运行;有潜在安全隐患,后续操作可能会改变其值

问题3:可以,不会影响输出。

 

 

 

任务4:

matrix.cpp

#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);               // 返回矩阵对象索引(i,j)的元素引用
    
    int get_lines() const;                  // 返回矩阵对象行数
    int get_cols() const;                   // 返回矩阵对象列数

    void display() const;                    // 按行显示矩阵对象元素值

private:
    int lines;      // 矩阵对象内元素行数
    int cols;       // 矩阵对象内元素列数
    double *ptr;
};

// 类Matrix的实现:待补足
// xxx
Matrix::Matrix(int n, int m) {
    lines = n;
    cols = m;
    ptr = new double[n * m];
}
Matrix::Matrix(int n) {
    lines = n;
    cols = 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 < cols * lines; i++) {
        ptr[i] = pvalue[i];
    }
}
void Matrix::clear() {
    for (int i = 0; i < cols * lines; i++) {
        ptr[i] = 0;
    }
}
const double& Matrix::at(int i, int j)const {
    return ptr[j*lines+i];
}
double& Matrix::at(int i, int j) {
    return ptr[j * lines + i];
}
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 << ptr[i * cols + j] << ", " ;
      
        }
        cout << "\b\b \n";
 
    }


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

运行结果:

 

 

 

任务5:

 user.hpp

#pragma once
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class User {
public:
    User(const string& n, const string& p = "123456", const string& e = "");
    void set_email();
    void change_password();
    void display()const;
private:
    string name;
    string password;
    string email;

};
User::User(const string& n, const string& p, const  string& e) {
    name = n;
    password = p;
    email = e;
}
void User::set_email() {
    cout << "Enter email address:";
    string em;
    cin >> em;
    while (1) {
        if (em.find('@') == string::npos)
        {
            cout << "illegal email.Please re-enter email:";
            cin >> em;
        }
        else {
            email = em;
            cout << "email is set sucessfully..." << endl;
            break;
        }

    }
}
void User::change_password() {
    cout << "Enter old password: ";
    string ppassword;
    string newpassword;
    cin >> ppassword;
    int h = 1;
    while(h<3) {
        if (password == ppassword) {
            cout << "Enter newpassword:";

            cin >> newpassword;
            password = newpassword;
            cout << "new password is set sucessfully..." << endl;
            break;
        }
        else
        {
            cout << "password input error.Please re-enter again: ";
            cin >> ppassword;
            h++;
        }

    }
    if (h == 3)cout << "password input error.Please try after a while" << endl;
}
void User::display() const {
    cout << "name:   " << name << endl;
    cout << "pass:   ";
    for (int i = 0; i < password.length(); i++)
        cout << "*";
    cout << endl;
    cout << "email:  " << 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", "[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();
}
View Code

运行结果:

 

 

 

 

任务6:

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;
    }
};
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;
    else
        return 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;
    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_H_ _
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");
        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 << "\tBalance:" << balance;
}
View Code

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)

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

 

运行结果:

 

标签:std,const,string,对象,编程,int,实验,vectorInt,include
From: https://www.cnblogs.com/bearrrr/p/18524996

相关文章

  • #Java-对象补充及字符串详讲
    0.类和对象深入解释在Java中,类(Class)和对象(Object)是两个核心概念,它们共同构成了面向对象编程(OOP)的基础。类(Class)定义:类是一个模板或蓝图,它描述了具有相同属性和行为的一组对象的共同特征。在Java中,类通过关键字class来定义。组成:类通常由成员变量(也称为属性或字段)和方......
  • SWJTU数电实验:可控分频计数器
    一、实验要求基本实验内容1、设计一个可控分频器,clk_in为分频器时钟输入(50MHz,已固定连接在PIN_90),sel为选择开关,clk_out[1:0]为分频器信号输出。当sel=0时,clk_out[0]=sn[3:0]Hz,clk_out[1]=sn[3:0]/2Hz;当sel=1时,clk_out[0]=sn[3:0]H......
  • 20222323 2024-2025-1 《网络与系统攻防技术》实验四实验报告
    1.实验内容一、恶意代码文件类型标识、脱壳与字符串提取对提供的rada恶意代码样本,进行文件类型识别,脱壳与字符串提取,以获得rada恶意代码的编写作者,具体操作如下:(1)使用文件格式和类型识别工具,给出rada恶意代码样本的文件格式、运行平台和加壳工具;(2)使用超级巡警脱壳机等脱壳软件,......
  • 实验3 类和对象_基础编程2
    一、实验目的加深对类的组合机制(has-a)的理解,会使用C++正确定义、使用组合类理解深复制、浅复制练习标准库string,vector用法,能基于问题场景灵活使用针对具体问题场景,练习运用面向对象思维进行设计,合理设计、组合类(自定义/标准库),编程解决实际问题二、实验内容1.实验任......
  • 代码江湖:一位编程侠客的历险记
    在一个风和日丽的早晨,我踏上了学习C语言的征途,满怀着对编程世界的憧憬和对未知的好奇。我想象自己将像一位英勇的骑士,挥舞着键盘和鼠标,征服一个又一个代码堡垒。然而,现实总是比想象中更加戏剧化,我的编程之旅充满了幽默和挑战。我首先遭遇的是PTA平台的挑战,它以其无情的题目和......
  • 实验3
    button.hpp#pragmaonce#include<iostream>#include<string>usingstd::string;usingstd::cout;//按钮类classButton{public:Button(conststring&text);stringget_label()const;voidclick();private:stringlabel;......
  • Socket编程与IO多路复用
    0、引言本篇博客将从socket模型为起点,引入IO多路复用的学习。1、Socket模型1.1、Socket的诞生Socket的诞生背景:Socket最早出现在20实际80年代的Unix操作系统中,当时计算机和网络技术逐步发展,分布式计算开始流行,操作系统需要提供一种标准化的网络通信方式来连接不同的设备。这......
  • 实验3 类和对象_基础编程2
    实验任务一源码1#pragmaonce23#include<iostream>4#include<string>56usingstd::string;7usingstd::cout;89//按钮类10classButton{11public:12Button(conststring&text);13stringget_label()const;14void......
  • 实验三 类和对象 基础编程2
    实验任务11,自定义了两个类分别是window类和button类使用了标准库中的iostream vectorstring 2,不适合 3定义了一个字符串长度为40实验任务21#include<iostream>2#include<vector>34usingnamespacestd;56voidoutput1(constvector<int>&v){......
  • stm32教程:GPIO口及流水灯实验
    早上好啊,大佬们,想必在你电脑硬盘的某处放着一个stm32的工程模板吧!~然后今天,就和大家一起写出第一个小项目——流水灯咱们先来讲讲GPIO口吧。关于GPIO的那点事儿什么是GPIOGPIO(英语:General-purposeinput/output),通用型之输入输出的简称,功能类似8051的P0—P3,其接脚可以供......