实验三

实验三:类和对象基础编程2

在本次实验中,使用的集成开发环境为Visual Studio Code与g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

实验任务1

1.编译指令与运行截图

image

2.问题回答

  1. 是的,是组合关系;
  2. 回答如下:
    (1) 优点:可以在外部查询是否已经存在这个按钮;缺点:个人认为,该功能在外部其实不会被调用,因为建立按钮的查重工作本就是Window这个类需要去完成的,而不应该作为公有接口暴露在外,破坏封装性的同时,容易造成误用;
    (2) 首先,public和private的建立主要还是要关注“是否会在外部被调用”,换言之,功能类的方法确实有必要对外展示,而内部的自检查,自适应以及运算等开发调试类的函数方法放在外面则显得累赘与危险;其次就是面向用户的需求,开发者需要将用户真正需要的功能封装为公有,而不关注的,只需要自己使用即可。
  3. 第一个引用第二个拷贝,前者不拷贝数据,而后者拷贝数据进入函数,前者会影响本体,而后者拷贝成本较高;
  4. 可正常运行,相比push,emplace的效率更高。

[摘录自CSDN] emplace_back与push_back的主要区别在于它们的实现机制。push_back在向vector尾部添加元素时,会先创建一个元素,然后将其拷贝或移动到容器中。如果是拷贝操作,之后会自动销毁创建的临时元素。而emplace_back则是直接在容器尾部创建元素,省去了这个中间步骤。

实验任务2

1.编译指令与运行截图

image
image

2.问题回答

  1. 第一行是带参数的构造,第二行是拷贝构造;都含5个42
  2. 2,2,3
  3. 两种的效果是一样的,查阅资料发现,at会检查越界,而[]就是最基础的随机存取
  4. 回答如下:
    (1) 可以的,因为调用size()方法返回对象长度的int值,-1后确实可以输出,而且不会越界
    (2) 可以节省内存,但是const不可以再进行修改
  5. 回答如下:
    (1) 深复制,因为修改之后不回影响原本的本体
    (2) 前者返回int的引用类型,后者返回const int的引用,必须要加const,

实验任务3

1.编译指令与运行截图

image

2.问题回答

  1. 在问题放出的代码中,上来就把数据区全部释放,对于自赋值而言无法实现;
  2. 回答如下:
    (1) 将非只读的vectorint的指针类型转换为只读模式的vectorint的指针类型
    (2) 移除/增加const的限定,不能改变对象本身的const属性,在这里应该是移除,返回类型从const int&变为int&,目的:在代码中实现const对象限定的修改操作,同时可以返回int的引用类型
  3. 回答如下:
    (1) v1调用非const接口,用于迭代修改,v2调用const接口,用于迭代读取遍历
  4. 可以,fill_n是从特定值向后填充同一个值,而指针的引入则可以填充序列;copy_n直接使用两个迭代器从源迭代器到目标迭代器进行拷贝操作

实验任务4

源代码

  1. matrix.hpp
#pragma once

#include <iostream>
#include <algorithm>
#include <cstdlib>

// 类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;    // 数据区
};

Matrix::Matrix(int rows_, int cols_, double value)
    : n_rows(rows_), n_cols(cols_) {
    ptr = new double[n_rows * n_cols];
    std::fill(ptr, ptr + n_rows * n_cols, value);
}

Matrix::Matrix(int rows_, double value){
    n_rows = rows_;
    n_cols = rows_;
    ptr = new double[n_rows * n_cols];
    std::fill(ptr, ptr + n_rows * n_cols, value);
}

Matrix::Matrix(const Matrix &x){
    n_cols = x.n_cols;
    n_rows = x.n_rows;
    ptr = new double[n_rows * n_cols];
    std::copy(x.ptr, x.ptr + n_rows * n_cols, ptr);
}

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

void Matrix::set(const double *pvalue, int size){
    if(size != n_rows*n_cols){
        std::cout << "ValueError: size mismatch in Matrix::set()\n";
        exit(1);
    }
    std::copy(pvalue, pvalue + size, ptr);
}

void Matrix::clear(){
    std::fill(ptr, ptr + n_rows * n_cols, 0);
}

double& Matrix::at(int i, int j){
    if(i < 0 || i >= n_rows || j < 0 || j >= n_cols){
        std::cout << "IndexError: index out of range in Matrix::at()\n";
        exit(1);
    }
    return ptr[i * n_cols + j];
}

const double& Matrix::at(int i, int j) const {
    if(i < 0 || i >= n_rows || j < 0 || j >= n_cols){
        std::cout << "IndexError: index out of range in Matrix::at()\n";
        exit(1);
    }
    return ptr[i * n_cols + j];
}

int Matrix::rows() const {
    return n_rows;
}

int Matrix::cols() const {
    return n_cols;
}

void Matrix::print() const {
    for (int i = 0; i < n_rows; i++)
    {
        for (int j = 0; j < n_cols; j++)
        {
            std::cout << at(i, j);
            if (j != n_cols - 1)
                std::cout << ", ";
        }
        std::cout << '\n';
    }
    
}
  1. task4.cpp
#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: ";
    std::cin >> n >> m;

    Matrix m1(n, m);    // 创建矩阵对象m1, 大小n×m
    m1.set(x, n*m);     // 用一维数组x的值按行为矩阵m1赋值

    Matrix m2(m, n);    // 创建矩阵对象m2, 大小m×n
    m2.set(x, m*n);     // 用一维数组x的值按行为矩阵m1赋值

    Matrix m3(n);       // 创建一个n×n方阵对象
    m3.set(x, 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";
        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::cout << '\n';
}

编译指令与运行截图

image

实验任务5

源代码

  1. contact.hpp
#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;   // 必填项
};

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;
}
  1. contactBook.hpp
# 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";
}

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
int ContactBook::index(const std::string &name) const{
    for (int i = 0; i < this->size(); i++)
    {
        if(contacts[i].get_name() == name)
            return i;
    }
    return -1;
}


// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录

void ContactBook::sort(){
    std::sort(contacts.begin(),contacts.end(),[](const Contact &a, const Contact &b){
        return a.get_name() < b.get_name();
    });
}
  1. task5.cpp
#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();
}

编译指令与运行截图

image

实验总结

  1. 本次实验做下来,感觉难度很大,我需要开始计算运行效率以及一些在我看来不是很重要实则很重要的东西,我最头疼的还是const,如果g++编译报错,又不知道哪里出了问题,vscode问题输出为0可以去查一下是不是const出问题了。
  2. C++中的指针感觉用处和C语言完全不一样,因为C++引入了引用类型&,所以在写程序的时候方便许多,因此指针和内存管理的应用变得难度更大了,但不得不说,new和delete相比malloc和free方便太多了
  3. 在最后实验五的时候,最后的字典序排序方法我知道使用算法库的std::sort函数,但是最后一个比较方法,vscode我自安装的代码不全在我长时间没有操作的情况下提示我使用lambda表达式[](const Contact &a, const Contact &b){ return a.get_name() < b.get_name(); }进行比较,但是我在查阅C++用户手册发现了字典序算法std::lexicographical_compare函数,我不知道可不可以用,但是最后我放弃了,因为我不知道如何安排参数,后来发现他输出的是bool类型,就放弃了。
posted @ 2025-11-23 18:27  As_Val  阅读(22)  评论(0)    收藏  举报