实验三 类和对象

##实验一

button.hpp

#pragma once

#include <iostream>
#include <string>

class Button {
public:
    Button(const std::string &label_);
    const std::string& get_label() const;
    void click();

private:
    std::string label;
};

Button::Button(const std::string &label_): label{label_} {
}

inline const std::string& Button::get_label() const {
    return label;
}

inline void Button::click() {
    std::cout << "Button '" << label << "' clicked\n";
}

 window.hpp

#include <iostream>
#include <vector>
#include <algorithm>
#include "button.hpp"

// 窗口类
class Window{
public:
    Window(const std::string &title_);
    void display() const;
    void close();
    void add_button(const std::string &label);
    void click_button(const std::string &label);

private:
    bool has_button(const std::string &label) const;

private:
    std::string title;
    std::vector<Button> buttons;
};

Window::Window(const std::string &title_): title{title_} {
    buttons.push_back(Button("close"));
}

inline void Window::display() const {
    std::string s(40, '*');
    std::cout << s << std::endl;
    std::cout << "window : " << title << std::endl;
    int cnt = 0;
    for(const auto &button: buttons)
        std::cout << ++cnt << ". " << button.get_label() << std::endl;
    std::cout << s << std::endl;
}

inline void Window::close() {
    std::cout << "close window '" << title << "'" << std::endl;
    click_button("close");
}

inline bool Window::has_button(const std::string &label) const {
    for(const auto &button: buttons)
        if(button.get_label() == label)
            return true;
    
    return false;
}

inline void Window::add_button(const std::string &label) {
    if(has_button(label))
        std::cout << "button " << label << " already exists!\n";
    else
        buttons.push_back(Button(label));
}

inline void Window::click_button(const std::string &label) {
    for(auto &button:buttons)
        if(button.get_label() == label) {
            button.click();
            return;
        }
            
    std::cout << "no button: " << label << std::endl;
}

task1.cpp

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

void test(){
    Window w("Demo");
    w.add_button("add");
    w.add_button("remove");
    w.add_button("modify");
    w.add_button("add");
    w.display();
    w.close();
}

int main() {
    std::cout << "用组合类模拟简单GUI:\n";
    test();
}

image

问题一:是。

问题二:(1)在改为公共接口后,破坏封装性,接口承诺问题,误用风险,但利于便利性,框架集成,与扩展性。

(2)

应设为 public 的情况:用户购买这个类就是为了获得这个功能,属于该类的主要职责和核心价值,没有这个方法,用户就无法完成他们的主要任务

应设为 private 的情况:只是实现核心功能的辅助手段。:涉及算法选择、数据结构、性能优化等实现技术,未来可能因技术演进而被完全重写或替换,只是为了让其他方法更容易实现而存在的工具函数等。

 

(3)接口1返回引用,通过文档明确使用约束即可规避风险;接口2返回的是副本,更加安全。

(4)能正常运行,这种替换会影响程序的正确性、安全性和性能,但避免临时对象的消失。

##实验二

task2.cpp

#include <iostream>
#include <vector>

void test1();
void test2();
void output1(const std::vector<int> &v);
void output2(const std::vector<int> &v);
void output3(const std::vector<std::vector<int>>& v);

int main() {
    std::cout << "深复制验证1: 标准库vector<int>\n";
    test1();

    std::cout << "\n深复制验证2: 标准库vector<int>嵌套使用\n";
    test2();
}

void test1() {
    std::vector<int> v1(5, 42);
    const std::vector<int> v2(v1);

    std::cout << "**********拷贝构造后**********\n";
    std::cout << "v1: "; output1(v1);
    std::cout << "v2: "; output1(v2);
    
    v1.at(0) = -1;

    std::cout << "**********修改v1[0]后**********\n";
    std::cout << "v1: "; output1(v1);
    std::cout << "v2: "; output1(v2); 
}

void test2() {
    std::vector<std::vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};
    const std::vector<std::vector<int>> v2(v1);

    std::cout << "**********拷贝构造后**********\n";
    std::cout << "v1: "; output3(v1);
    std::cout << "v2: "; output3(v2);

    v1.at(0).push_back(-1);

    std::cout << "**********修改v1[0]后**********\n";
    std::cout << "v1: \n";  output3(v1);
    std::cout << "v2: \n";  output3(v2);
}

// 使用xx.at()+循环输出vector<int>数据项
void output1(const std::vector<int> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }
    
    std::cout << v.at(0);
    for(auto i = 1; i < v.size(); ++i)
        std::cout << ", " << v.at(i);
    std::cout << '\n';  
}

// 使用迭代器+循环输出vector<int>数据项
void output2(const std::vector<int> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }
    
    auto it = v.begin();
    std::cout << *it;

    for(it = v.begin()+1; it != v.end(); ++it)
        std::cout << ", " << *it;
    std::cout << '\n';
}

// 使用auto for分行输出vector<vector<int>>数据项
void output3(const std::vector<std::vector<int>>& v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }

    for(auto &i: v)
        output2(i);
}

image

 (1)问题一:构造函数和拷贝构造函数; 都包含5个。

(2)2 2 3

(3)能,v1[0] = -1,更快但会有数据出错的风险。

(4)1.能,用size()来方法返回对象长度的int值,输出-1。

2.避免不必要的复制,从而节省内存,但用const只能读取。

(5)1.深复制。2.int &   const int &     是。

##实验三

vectorInt.hpp

#pragma once

#include <iostream>


class vectorInt{
public:
    vectorInt();
    vectorInt(int n_);
    vectorInt(int n_, int value);
    vectorInt(const vectorInt &vi);
    ~vectorInt();
    
    int size() const;
    int& at(int index);
    const int& at(int index) const;
    vectorInt& assign(const vectorInt &vi);

    int* begin();
    int* end();
    const int* begin() const;
    const int* end() const;

private:
    int n;     
    int *ptr;  
};

vectorInt::vectorInt():n{0}, ptr{nullptr} {
}

vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {
}

vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = value;
}

vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
    for(auto i = 0; i < n; ++i)
        ptr[i] = vi.ptr[i];
}

vectorInt::~vectorInt() {
    delete [] ptr;
}

int vectorInt::size() const {
    return n;
}

const int& vectorInt::at(int index) const {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

int& vectorInt::at(int index) {
    if(index < 0 || index >= n) {
        std::cerr << "IndexError: index out of range\n";
        std::exit(1);
    }

    return ptr[index];
}

vectorInt& vectorInt::assign(const vectorInt &vi) { 
    if(this == &vi) 
        return *this;

    int *ptr_tmp;
    ptr_tmp = new int[vi.n];
    for(int i = 0; i < vi.n; ++i)
        ptr_tmp[i] = vi.ptr[i];
    
    delete[] ptr;
    n = vi.n;
    ptr = ptr_tmp;
    return *this;
}

int* vectorInt::begin() {
    return ptr;
}

int* vectorInt::end() {
    return ptr+n;
}

const int* vectorInt::begin() const {
    return ptr;
}

const int* vectorInt::end() const {
    return ptr+n;
}

task3.cpp

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

void test1();
void test2();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);

int main() {
    std::cout << "测试1: \n";
    test1();

    std::cout << "\n测试2: \n";
    test2();
}

void test1() {
    int n;
    std::cout << "Enter n: ";
    std::cin >> n;

    vectorInt x1(n);
    for(auto i = 0; i < n; ++i)
        x1.at(i) = (i+1)*10;
    std::cout << "x1: ";  output1(x1);

    vectorInt x2(n, 42);
    vectorInt x3(x2);
    x2.at(0) = -1;
    std::cout << "x2: ";  output1(x2);
    std::cout << "x3: ";  output1(x3);
}

void test2() {
    const vectorInt  x(5, 42);
    vectorInt y;

    y.assign(x);

    std::cout << "x: ";  output2(x);
    std::cout << "y: ";  output2(y);
}

void output1(const vectorInt &vi) {
    if(vi.size() == 0) {
        std::cout << '\n';
        return;
    }
        
    std::cout << vi.at(0);
    for(auto i = 1; i < vi.size(); ++i)
        std::cout << ", " << vi.at(i);
    std::cout << '\n';
}

void output2(const vectorInt &vi) {
    if(vi.size() == 0) {
        std::cout << '\n';
        return;
    }
    
    auto it = vi.begin();
    std::cout << *it;

    for(it = vi.begin()+1; it != vi.end(); ++it)
        std::cout << ", " << *it;
    std::cout << '\n';
}

image

 问题一:(1)版本2缺少自赋值检查。

(2)1.将当前对象的指针从非常量转换为常量指针,vectorInt*,const vectorInt*。

2.移除const修饰符,使返回值可以用于修改操作 ,转换前this返回类型是const int& 转换后返回类型是int&,满足非const接口的返回类型要求。

(3) const版本:用于只读访问对象的场景,非const修改元素的场景。

(4)可以,std::fill(ptr, ptr + n, value):将ptr开始的n个元素都设置为value   std::copy(vi.ptr, vi.ptr + vi.n, ptr):从vi.ptr复制n个元素到ptr。

##实验四

matrix.hpp

1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 #pragma once
 // 类Matrix声明
class Matrix {
 public:
 Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value
 Matrix(int rows_, double value = 0);    
// 构造rows_*rows_方阵对象, 初值value
 Matrix(const Matrix &x);    
~Matrix();
 // 深复制
void set(const double *pvalue, int size);   // 按行复制pvalue指向的数据,要求
size=rows*cols,否则报错退出
void clear();   // 矩阵对象数据项置0
 const double& at(int i, int j) const;   // 返回矩阵对象索引(i,j)对应的数据项const引用(越
界则报错后退出)
double& at(int i, int j);   // 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
int rows() const;   // 返回矩阵对象行数
int cols() const;   // 返回矩阵对象列数
void print() const;   // 按行打印数据
private:
 int n_rows;      
int n_cols;       
double *ptr;    
};
 task4.cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 #include <iostream>
 #include <cstdlib>
 #include "matrix.hpp"
 // 矩阵对象内元素行数
// 矩阵对象内元素列数
// 数据区
void test1();
 void test2();
 void output(const Matrix &m, int row_index);
 int main() {
 std::cout << "测试1: \n";
 test1();
 }
 std::cout << "\n测试2: \n";
 test2();
 void test1() {
 double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 int n, m;
 std::cout << "Enter n and m: ";
22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 std::cin >> n >> m;
 Matrix m1(n, m);    
m1.set(x, n*m);     
Matrix m2(m, n);    
m2.set(x, m*n);     
Matrix m3(n);       
m3.set(x, n*n);     
// 创建矩阵对象m1, 大小n×m
 // 用一维数组x的值按行为矩阵m1赋值
// 创建矩阵对象m2, 大小m×n
 // 用一维数组x的值按行为矩阵m1赋值
// 创建一个n×n方阵对象
// 用一维数组x的值按行为矩阵m3赋值
std::cout << "矩阵对象m1: \n";   m1.print();
 std::cout << "矩阵对象m2: \n";   m2.print();
 std::cout << "矩阵对象m3: \n";   m3.print();
 }
 void test2() {
 Matrix m1(2, 3, -1);
 const Matrix m2(m1);
 std::cout << "矩阵对象m1: \n";   m1.print();
 std::cout << "矩阵对象m2: \n";   m2.print();
 m1.clear();
 m1.at(0, 0) = 1;
 std::cout << "m1更新后: \n";
 std::cout << "矩阵对象m1第0行 "; output(m1, 0);
 std::cout << "矩阵对象m2第0行: "; output(m2, 0);
 }
 // 输出矩阵对象row_index行所有元素
void output(const Matrix &m, int row_index) {
 if(row_index < 0 || row_index > m.rows()) {
 std::cerr << "IndexError: row index out of range\n";
 std::exit(1);
 }
 std::cout << m.at(row_index, 0);
 for(int j = 1; j < m.cols(); ++j)
 std::cout << ", " << m.at(row_index, j);
 std

 

#include "matrix.hpp"

#include <iostream>

#include <stdexcept>
#include <iomanip>


Matrix::Matrix(size_t rows, size_t cols) : rows_(rows), cols_(cols) {
if (rows == 0 || cols == 0) {
throw std::invalid_argument("Matrix dimensions must be positive");
}

data_ = new int[rows * cols];

for (size_t i = 0; i < rows * cols; ++i) {
data_[i] = 0;
}
}


Matrix::Matrix(size_t n) : rows_(n), cols_(n) {
if (n == 0) {
throw std::invalid_argument("Matrix dimension must be positive");
}

data_ = new int[n * n];

for (size_t i = 0; i < n * n; ++i) {
data_[i] = 0;
}
}


Matrix::Matrix(const Matrix& other) : rows_(other.rows_), cols_(other.cols_) {
data_ = new int[rows_ * cols_];


for (size_t i = 0; i < rows_ * cols_; ++i) {
data_[i] = other.data_[i];
}
}

}

Matrix& Matrix::operator=(const Matrix& other) {
if (this == &other) {
return *this; 
}

delete[] data_;

rows_ = other.rows_;
cols_ = other.cols_;
data_ = new int[rows_ * cols_];

for (size_t i = 0; i < rows_ * cols_; ++i) {
data_[i] = other.data_[i];
}

return *this;
}

Matrix::~Matrix() {
delete[] data_;
}


size_t Matrix::getRows() const {
return rows_;
}

size_t Matrix::getCols() const {
return cols_;
}

int& Matrix::at(size_t row, size_t col) {
checkBounds(row, col);
return data_[row * cols_ + col];
}

const int& Matrix::at(size_t row, size_t col) const {
checkBounds(row, col);
return data_[row * cols_ + col];
}

void Matrix::checkBounds(size_t row, size_t col) const {
if (row >= rows_ || col >= cols_) {
throw std::out_of_range("Matrix index out of range");
}
}

void Matrix::print() const {
for (size_t i = 0; i < rows_; ++i) {
for (size_t j = 0; j < cols_; ++j) {
std::cout << std::setw(4) << at(i, j);
}
std::cout << std::endl;
}
}


 

image

##实验五


#pragma once
#include
<iostream> #include <string> // class Contact { public: Contact(const std::string &name_, const std::string &phone_); const std::string &get_name() const; const std::string &get_phone() const; void display() const; private: std::string name; std::string phone;
1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 # pragma  once
 #include <iostream>
 #include <string>
 #include <vector>
 #include <algorithm>
 #include "contact.hpp"
 // 通讯录类
class ContactBook {
 public:
 void add(const std::string &name, const std::string &phone); // 添加联系人
void remove(const std::string &name); // 移除联系人
void find(const std::string &name) const; // 查找联系人
void display() const; // 显示所有联系人
size_t size() const;
 private:
 int index(const std::string &name) const;  // 返回联系人在contacts内索引,如不存在,返
回-1
 void sort(); // 按姓名字典序升序排序通讯录
private:
 std::vector<Contact> contacts;
 };
 }
 void ContactBook::add(const std::string &name, const std::string &phone) {
 if(index(name) == -1) {
 contacts.push_back(Contact(name, phone));
 std::cout << name << " add successfully.\n";
 sort();
 return;
 }
 std::cout << name << " already exists. fail to add!\n"; 
void ContactBook::remove(const std::string &name) {
 int i = index(name);
 if(i == -1) {
 std::cout << name << " not found, fail to remove!\n";
 return;
 }
 contacts.erase(contacts.begin()+i);
 std::cout << name << " remove successfully.\n";
 }
task5.cpp
 void ContactBook::find(const std::string &name) const {
    int i = index(name);
    if(i == -1) {
        std::cout << name << " not found!\n";
        return;
    }
    contacts[i].display(); 
    std::cout << '\n';
 }
 void ContactBook::display() const {
    for(auto &c: contacts) {
        c.display(); 
        std::cout << '\n';
    }
 }
 size_t ContactBook::size() const {
    return contacts.size();
 }
 // 待补足1:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
 // 待补足2:void ContactBook::sort();实现
#include "contactBook.hpp"

void test() {
    ContactBook contactbook;

    std::cout << "1. add contacts\n";
    contactbook.add("Bob", "18199357253");
    contactbook.add("Alice", "17300886371");
    contactbook.add("Linda", "18184538072");
    contactbook.add("Alice", "17300886371");

    std::cout << "\n2. display contacts\n";
    std::cout << "There are " << contactbook.size() << " contacts.\n";
    contactbook.display();

    std::cout << "\n3. find contacts\n";
    contactbook.find("Bob");
    contactbook.find("David");

    std::cout << "\n4. remove contact\n";
    contactbook.remove("Bob");
    contactbook.remove("David");
}

int main() {
    test();
}

 


};

Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {
}

const std::string& Contact::get_name() const {
    return name;
}

const std::string& Contact::get_phone() const {
    return phone;
}

void Contact::display() const {
    std::cout << name << ", " << phone;
}

 

image

 

 

 

 

posted @ 2025-11-25 22:42  石朗鹏  阅读(6)  评论(1)    收藏  举报