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

实验任务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:

两个类,按钮类和窗口类。

Std::string

Std::vector

Std::cout

Std:cin

Std::endl

问题2:
不适合;

没加const是因为它输出信息但不改变Button的状态

没加inline是因为包含逻辑较多的操作

问题3:
创建一个std::string对象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();
}


问题1:
创建一个std::vector<int>对象v1,并将其初始化为5个元素,每个元素都为42的向量

创建一个std::vector<int>对象v2,并将其初始化v1

将v1中的第一个元素赋为-999

 

问题2:
创建一个二维的std::vector<int>对象v1,初始化为{1,2,3},{4,5,6,7}

通过复制构造函数创建v2,v2是v1的深复制

访问v1中的第一个vector,并在其末尾添加一个整数-999

 

问题3:
创建一个一维的std::vector<int>对象t1,将其初始化为v1的第一个元素,即{1,2,3}

输出t1的最后一个元素并回车

从v2中获取第一个vector的一个const拷贝

输出t2的最后一个元素并回车
问题4:
①深复制

②是

 

 

 

实验任务3:
代码:
vectorlnt.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;
}

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

问题1:
深复制

 

问题2:

不能正常运行

有安全隐患

原因:去掉 const 会导致 const vectorInt 对象无法调用该方法,因为它会破坏常量对象的不可变性,所以这种情况下会存在潜在的安全隐患。

 

问题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的矩阵
    Matrix(int n); // 构造函数,构造一个n*n的矩阵
    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; // 指向动态分配的二维矩阵内存块
};

// 构造一个n*m的矩阵
Matrix::Matrix(int n, int m) : lines{n}, cols{m}, ptr{new double[n * m]} {
    for (int i = 0; i < lines * cols; ++i) {
        ptr[i] = 0.0;
    }
}

// 构造一个n*n的矩阵
Matrix::Matrix(int n) : Matrix(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];
    }
}

// 析构函数,释放动态内存
Matrix::~Matrix() {
    delete[] ptr;
}

// 用pvalue指向的连续内存块数据按行赋值
void Matrix::set(const double *pvalue) {
    for (int i = 0; i < lines * cols; ++i) {
        ptr[i] = pvalue[i];
    }
}

// 把矩阵对象的值置0
void Matrix::clear() {
    for (int i = 0; i < lines * cols; ++i) {
        ptr[i] = 0.0;
    }
}

// 返回矩阵对象索引(i, j)的元素的const引用
const double& Matrix::at(int i, int j) const {
    assert(i >= 0 && i < lines);
    assert(j >= 0 && j < cols);
    return ptr[i * cols + j];
}

// 返回矩阵对象索引(i, j)的元素引用
double& Matrix::at(int i, int j) {
    assert(i >= 0 && i < lines);
    assert(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] = {123, 234, 345, 456, 567, 678, 789, 890, 901};

    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>
#include <cassert>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class User {
public:
    User(const string& name, const string& password = "123456", const string& email = "")
        : name{name}, password{password}, email{email} {}

    void set_email() {
        while (true) {
            cout << "Enter email address: ";
            cin >> email;
            if (is_valid_email(email)) {
                cout << "email is set successfully...\n";
                break;
            } else {
                cout << "illegal email. Please re-enter email: ";
            }
        }
    }

    void change_password() {
        string old_password;
        int attempts = 0;
        while (attempts < 3) {
            cout << "Enter old password: ";
            cin >> old_password;
            if (old_password == password) {
                string new_password;
                cout << "Enter new password: ";
                cin >> new_password;
                password = new_password;
                cout << "new password is set successfully...\n";
                return;
            } else {
                attempts++;
                if (attempts < 3) {
                    cout << "password input error. Please re-enter again: ";
                } else {
                    cout << "password input error. Please try after a while.\n";
                }
            }
        }
    }

    void display() const {
        cout << "name: " << name << endl;
        cout << "pass: " << string(password.size(), '*') << endl;
        cout << "email: " << email << endl;
    }

private:
    string name;
    string password;
    string email;

    bool is_valid_email(const string& email) const {
        auto pos = email.find("@");
        return pos != string::npos && pos != 0 && pos != email.size() - 1;
    }
};

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

 

 

 

实验任务6:

代码:

date.hpp

查看代码

 #pragma once

#include<iostream>
#include<cstdlib>

using namespace std;
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;
        }
};
namespace {
    const int DAYS_BEFIRE_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_BEFIRE_MONTH[month - 1] + day;
    if (isLeapYear() && month > 2) totalDays++;
}
int Date::getMaxDay()const {
    if (isLeapYear() &&month == 2)
        return 29;
    else return DAYS_BEFIRE_MONTH[month] - DAYS_BEFIRE_MONTH[month - 1];
}
void Date::show()const {
    cout << getYear() << "-" << getMonth() << "-" << getDay();
}

account.hpp

查看代码

 #pragma once

#include"date.hpp"
#include<string>
#include<cmath>
#include<iostream>

using namespace std;

class SavingsAccount {
    private:
        string id;
        double balance;
        double rate;
        Date lastDate;
        double accumulation;
        static double total;
        void record(const Date& date, double amount, const string& desc);
        void error(const string& msg) const;
        double accumulate(const Date& date)const {
            return accumulation + balance * date.distance(lastDate);
        }
    public:
        SavingsAccount(const Date& date, const string& id, double rate);
        const 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 string& desc);
        void withdraw(const Date& date, double amount, const string& desc);
        void settle(const Date& date);
        void show() const;
};
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;
}

6_25.cpp

查看代码

 #include"account.hpp"
#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;
}

posted @ 2024-11-10 22:52  夏日华  阅读(3)  评论(0编辑  收藏  举报