Task3

任务1

  • 运行测试截图:5df2164e7ff94d6036ff508d2f2ab5d4

问题1:window和button是组合关系,window对象和button这个成员变量共同被创建和销毁,符合整体与部分同生共死。
问题2:1.优点是方便外部代码查询,缺点是安全性降低
2.当外部需要了解按钮是否存在是使用public,当内部需要实现细节时用private
问题3:接口1是返还引用,接口2是返回值,接口1需要拷贝,直接返还lable_引用,接口2每次要调用一个新的 std::string 对象,安全性上接口1只读外部不修改内部状态,保证了封装性,但如果调用者保存了引用,而原对象被销毁,引用将失效,接口2返回一个独立的副本,更安全,性能会损耗。
问题4:1.push_back(Button(label)):首先在外部构造一个临时的 Button 对象,然后将该临时对象移动或拷贝到 vector 的末尾。涉及一次临时对象的构造和一次移动构造。emplace_back(label):直接在 vector 的末尾内存位置上原地构造 Button 对象。将参数 label 直接传递给 Button 的构造函数。总而言之,emplace_back 避免了临时对象的创建和移动/拷贝开销,效率更高。在现代 C++ 中,通常推荐使用 emplace_back。
2.可以。std::any_of() 简述:
功能:检查给定范围 [first, last) 内是否存在至少一个元素满足特定条件(谓词)。
参数:first, last:迭代器范围,指定要检查的容器区间(这里是 buttons_.begin() 到 buttons_.end())。p:一元谓词(Unary Predicate),即一个返回 bool 的函数或 Lambda 表达式(这里是 [&](const Button &b) { return b.get_label() == label; })。返回值:bool。如果范围中至少有一个元素使谓词返回 true,则返回 true;如果范围为空或所有元素都返回 false,则返回 false。
3.可以。std::find_if() 简述:
功能:在给定范围 [first, last) 内查找第一个满足特定条件(谓词)的元素。
参数:first, last:迭代器范围(buttons_.begin(), buttons_.end())。p:一元谓词(Lambda 表达式,判断 b.get_label() == label)。返回值:返回一个迭代器。如果找到满足条件的元素,返回指向第一个满足条件的元素的迭代器。如果未找到,返回 last(即 buttons_.end())。

任务2

  • 运行测试截图:03432fc0182929c515279c906c092064
    问题1:std::vector v1(5, 42);:调用的是vector的填充构造函数,v1包含5个值为42的数据项
    const std::vector v2(v1);:调用的是vector的拷贝构造函数,v2拷贝的v1同样包含5个值为42的数据项。
    问题2:v1.size()是2,因为v1包含两个内层;vectorv2.size()是2和v1相同;v1[0].size()是3第一个内层vector包含元素 1, 2, 3)
    问题3:能。两者的目的都是修改v1的第一个元素为-1;at()进行边界检查。如果索引越界,会抛出 std::out_of_range异常,程序可以被捕获并处理,更加安全,但会有轻微的性能开销。
    问题4:1.可以。const std::vector &r将这个引用绑定到了v1的第一个元素上。由于r是引用,它直接反映了v1[0]的最新状态。
    2.优势避免拷贝,缺点由于const引用不能通过r修改它引用的数据
    问题5:1.深拷贝,修改v1[0]后,v2[0]并未改变
    3.当v是vector时,v.at(0)的返回值类型是int&;当 v 是 const vector 时,v.at(0)的返回值类型是const int&;必须提供带const修饰的重载版本,因为C++允许对常量对象调用成员函数,如果 at() 只有非const版本,那么const vector对象就无法调用at()方法(编译器会报错)

任务3

  • 运行测试截图:66426098ad1962357d9c059f3aedd315
    问题1:版本二代码:inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    delete[] pdata_; // 危险操作1
    n_ = vi.n_;
    pdata_ = new int[n_];
    for(auto i = 0; i < n_; ++i)
    pdata_[i] = vi.pdata_[i]; // 危险操作2
    return this;
    }
    缺陷一:导致悬垂指针和未定义行为。原安全版本首先执行了 if(this == &vi) return this;。如果传入的是对象自身,直接返回,避免后续操作。
    版本2没有这个检查。当 x.assign(x) 执行时,第一行 delete[] pdata_; 释放了 x 内部的数据区。此时,形参 vi 是 x 的引用,因此 vi.pdata_ 也随之变成了悬垂指针(指向已释放的内存)。
    缺陷二:读取已释放的内存。在 delete[] pdata_; 之后,代码执行 pdata_ = new int[n_];。虽然 pdata_ 重新分配了内存,但形参 vi.pdata_ 依然指向旧的内存地址。
    在 for 循环中,pdata_[i] = vi.pdata_[i]; 试图从已被释放的 vi.pdata_ 中读取数据,这是典型的使用后释放(Use-After-Free)漏洞,会导致程序崩溃或产生不可预知的数据损坏。
    缺陷三:内存泄漏。版本2在 delete[] pdata_ 之后立即执行 new。如果 new 因为内存不足抛出 std::bad_alloc 异常,pdata_ 已经被释放,对象处于无效状态,且没有异常安全保证(原版是先分配新内存,成功后再释放旧内存,提供强异常安全保证)。
    问题2:1.作用:将当前对象的 this 指针(非 const 版本)强制转换为指向常量对象的指针(const vectorInt
    )。
    转换前类型:vectorInt
    (因为是在非 const 成员函数 int& at(int index) 内部)。
    转换后类型:const vectorInt。
    转换目的:为了调用 const 版本的 at() 成员函数,从而复用其边界检查逻辑,避免代码重复。
    2.作用:移除常量属性(const),将常量引用转换为非常量引用。
    转换前返回类型:const int& (因为调用的 const 版本 at() 返回的是 const int&)。
    转换后返回类型:int&。
    转换目的:因为非 const 版本的 at() 接口约定要返回可修改的 int&,而内部复用的 const 版本返回的是只读的 const int&,所以必须通过 const_cast 去除常量性,以匹配外层函数的返回类型。
    问题3:it1 = v1.begin();:调用非 const 版本(返回 int
    )。因为 v1 是一个非 const 对象,编译器优先匹配非 const 成员函数。
    it2 = v2.begin();:调用const 版本(返回 const int*)。因为 v2 是 const 对象,只能调用 const 成员函数。
    适配场景总结:
    非 const 版本:适用于需要修改对象内部数据的场景(如遍历并修改元素)。
    const 版本:适用于只读场景(如打印输出、计算),或者操作 const 对象时使用,保证对象状态不被意外修改。

任务4

  • 运行测试截图:5345153f0c1bbd2253606111f950dced
    补全代码:matrix.cpp
    #include "matrix.h"
    #include
    #include
    #include
    #include
Matrix::Matrix(int n_rows, int n_cols, double value)
n_rows_{n_rows}, n_cols_{n_cols}, pdata_{new double[n_rowsn_cols]} {
std::fill_n(pdata_, n_rows
n_cols, value);
}

Matrix::Matrix(int n_rows, double value): Matrix(n_rows, n_rows, value) {
}

Matrix::Matrix(const Matrix &x) {
n_rows_ = x.n_rows_;
n_cols_ = x.n_cols_;
pdata_ = new double[n_rows_ * n_cols_];
for (int i = 0; i < n_rows_ * n_cols_; ++i) {
pdata_[i] = x.pdata_[i];
}
}

Matrix::~Matrix() {
delete[] pdata_;
pdata_ = nullptr;
}

void Matrix::set(const double *pvalue, int size) {
if(size != n_rows_ * n_cols_)
throw std::invalid_argument("size must match");

std::copy_n(pvalue, size, pdata_);
}

void Matrix::clear() {
std::fill_n(pdata_, n_rows_ * n_cols_, 0);
}

const double& Matrix::at(int i, int j) const {
if(i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_)
throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]");

return pdata_[i * n_cols_ + j];
}

double& Matrix::at(int i, int j) {
if (i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_) {
throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]");
}
return pdata_[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 << pdata_[i * n_cols_ + j];
if (j != n_cols_ - 1) {
std::cout << ", ";
}
}
std::cout << std::endl;
}
}

任务5:

  • 运行测试截图:02f3f451e72c73034cfc53551d593e8e
    补写代码部分:
    inline int ContactBook::index(const std::string &name) const {
    for (size_t i = 0; i < contacts_.size(); ++i) {
    if (contacts_[i].get_name() == name) {
    return i;
    }
    }
    return -1;
    }

inline void ContactBook::sort() {
std::sort(contacts_.begin(), contacts_.end(),
[](const Contact &a, const Contact &b) {
return a.get_name() < b.get_name();
});
}

补全后全部代码:contact.hpp

pragma once

include

include

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

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

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

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

inline void Contact::display() const {
std::cout << name_ << ", " << phone_;
}
contactBook.hpp

pragma once

include "contact.hpp"

include

include

include

include

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;
void sort();

private:
std::vector contacts_;
};

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

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

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

inline void ContactBook::display() const {
for(auto &c: contacts_) {
c.display();
std::cout << '\n';
}
}

inline size_t ContactBook::size() const {
return contacts_.size();
}

inline int ContactBook::index(const std::string &name) const {
for (size_t i = 0; i < contacts_.size(); ++i) {
if (contacts_[i].get_name() == name) {
return i;
}
}
return -1;
}

inline void ContactBook::sort() {
std::sort(contacts_.begin(), contacts_.end(),
[](const Contact &a, const Contact &b) {
return a.get_name() < b.get_name();
});
}
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");

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

int main() {
test();
}

实验总结:

对于深拷贝有了更深层次理解,深拷贝不仅复制对象本身的所有成员变量值,对于对象内部持有的指针所指向的动态内存,以vectorInt为例,如果类管理了像new int[]这种,必须实现深拷贝,这样即使分配新内存失败抛出异常,原对象状态也不会被破坏。
但是对标准库使用以及对类的组合这些还是存在很大不足,实验五还是无法独立完成,最终还得AI出大部分力。

posted @ 2026-12-03 22:04  kk库拉索  阅读(3)  评论(0)    收藏  举报