实验3

任务一

源代码

点击查看代码
window.hpp
#pragma once
#include "button.hpp"
#include <iostream>
#include <vector>
#include <algorithm>
// 窗口类
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;
std::string title_;
std::vector<Button> buttons_;
};
inline 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;
}
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_;
};
inline 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";
}
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();
return 0;
}

运行结果截图

image

问题与讨论

问题1:是组合关系,在window类中,buttons_被声明为std::vectorButtonbuttons_;这里使用的是值。Button对象的生命周期完全由Window对象掌控着,如果Window被销毁,里面的按钮也会跟着消失。
问题2:1.优点:外部可以直接查询。缺点:破坏了封装性,暴露内部实现细节,如果Window的内部代码发生变化,那么公共接口会导致大量代码需要重构。
2.如果是类对外提供的接口,设为public。如果仅仅属于内部细节,设为private。
问题3:const std::string& get_label() const性能高,返回的是引用,避免了拷贝。安全性高,返回值加了const,表明调用的时候只读但不能修改,保证了数据封装的安全性。
问题4:1.程序能正常运行,且功能完全一样;push_back(Button("close")) 会先构造一个临时的 Button 对象,然后把这个临时对象拷贝/移动到 vector 的内存空间中,最后销毁临时对象(构造 + 拷贝/移动 + 析构)。emplace_back("close") 是原地构造。它直接将参数 "close" 完美转发给 vector 底层内存,在那里直接调用 Button 的构造函数创建对象。省去了临时对象的构造和拷贝/移动,性能更高。
2.可以。std::any_of 的功能:检查给定范围内(如 buttons_.begin() 到 buttons_.end())是否存在至少一个满足特定条件的元素。参数:1. 起始迭代器;2. 结束迭代器;3. 一个一元谓词(通常用 Lambda 表达式),返回 true 或 false。返回值:如果找到任何一个满足谓词的元素,返回 true;如果遍历完都没找到,返回 false。
3.可以。std::find_if 的功能:在指定范围内查找第一个满足特定条件的元素。参数:1. 起始迭代器;2. 结束迭代器;3. 一个一元谓词。返回值:返回指向第一个满足条件的元素的迭代器。如果没找到,则返回第二个参数(即结束迭代器 buttons_.end())。

任务二

源代码

点击查看代码
#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();
return 0;
}
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[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:\n"; output3(v1);
std::cout << "v2:\n"; output3(v2);
v1[0].push_back(-1);
std::cout << "**********修改v1[0]后**********\n";
std::cout << "v1:\n"; output3(v1);
std::cout << "v2:\n"; output3(v2);
}
// 使用索引+循环,遍历输出vector<int>数据项
void output1(const std::vector<int> &v) {
if(v.size() == 0) {
std::cout << '\n';
return;
}
std::cout << v[0];
for(auto i = 1; i < v.size(); ++i)
std::cout << ", " << v[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个值为42的数据项。
问题2:2,2,3
问题3:能,[]不进行越界检查,如果越界访问,编译器会直接崩溃。.at()会进行安全检查。
问题4:1.能,v1[0].push_back(-1); 是直接修改了v1内部第一个vector的元素,const std::vector&r = v1[0];定义了一个常量引用r绑定到修改后的v1[0]上。2.优势:引用零拷贝,const保证只读;限制:r只是别名,不能修改内部元素。
问题5:1.深拷贝。2.当v是vector时,v.at(0)返回值类型是 int&。当v是const vector时,v.at(0)返回值类型是const int&。必须提供。

任务三

源代码

点击查看代码
vectorInt.hpp
#pragma once
#include <iostream>
#include <stdexcept>
// 动态int数组对象类
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 *pdata_; // 数据区
};
inline vectorInt::vectorInt():n_{0}, pdata_{nullptr} {
}
inline vectorInt::vectorInt(int n): n_{n}, pdata_{new int[n]} {
}
inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} {
for(auto i = 0; i < n_; ++i)
pdata_[i] = value;
}
inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} {
for(auto i = 0; i < n_; ++i)
pdata_[i] = vi.pdata_[i];
}
inline vectorInt::~vectorInt() {
delete [] pdata_;
}
inline int vectorInt::size() const {
return n_;
}
inline const int& vectorInt::at(int index) const {
if(index < 0 || index >= n_)
throw std::out_of_range("vectorInt::at: index out of range");
return pdata_[index];
}
inline int& vectorInt::at(int index) {
if(index < 0 || index >= n_)
throw std::out_of_range("vectorInt::at: index out of range");
return pdata_[index];
}
inline vectorInt& vectorInt::assign(const vectorInt &vi) {
if(this == &vi)
return *this;
int *ptr;
ptr = new int[vi.n_];
for(int i = 0; i < vi.n_; ++i)
ptr[i] = vi.pdata_[i];
delete[] pdata_;
n_ = vi.n_;
pdata_ = ptr;
return *this;
}
inline int* vectorInt::begin() {
return pdata_;
}
inline int* vectorInt::end() {
return pdata_ + n_;
}
inline const int* vectorInt::begin() const {
return pdata_;
}
inline const int* vectorInt::end() const {
return pdata_ + n_;
}
task3.cpp
#include "vectorInt.hpp"
#include <iostream>
void test1();
void test2();
void test3();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);
int main() {
std::cout << "测试1: 构造、更新\n";
test1();
std::cout << "\n测试2: const对象、赋值\n";
test2();
std::cout << "\n测试3: 赋值\n";
test3();
return 0;
}
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);
y.at(0) = -1;
std::cout << "x: "; output2(x);
std::cout << "y: "; output2(y);
}
void test3() {
	vectorInt x(5, 42);
std::cout << "x: "; output2(x);
x.assign(x);
std::cout << "x: "; output2(x);
}
// 使用xx.at()+循环输出vectorInt对象数据项
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';
}
// 使用迭代器+循环输出vectorInt对象数据项
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:程序崩溃,当执行x.assign(x)时,this指针和传入的&vi指向同一个对象。接着pdata_ = new int[n_];此时vi.pdata_已经变成了野指针。在pdata_[i]=vi.pdata_[i];时,实际上是在尝试读取已被释放的内存,导致程序崩溃。
问题2:1.static_cast<const vectorInt>(this) 的作用:转换前的类型;vectorInt(因为这是在非 const 成员函数里,this 默认是指向非 const 的指针)。转换后的类型:const vectorInt(指向常量的指针)。转换目的:因为我们要调用const版本的 at(),它要求对象本身必须是const的。加上const属性后,代码就可以匹配到const int& at(int) const接口。安全性:这是安全的。给指针加上 const 限制(增加只读性)是绝对安全的。2.const_cast<int&> 的作用:转换前的类型:const int&(由内部的 at() 返回)。转换后的类型:int&(普通的、可修改的引用)。转换目的:外层函数是非 const 版本,它承诺允许用户修改返回的引用。因此,必须把内层 at() 返回的 const 属性“强转”掉(const_cast 的专属用途),变成普通引用返回给用户。安全性:这也是安全的。因为原始的this指针本来就指向一个非const对象,只是刚才被我们临时当成了const用了一下。去const化后,修改原数据是合法的。
问题3:1.编译器会根据调用该函数的对象是否是const对象来匹配。v1是普通对象,所以v1.begin()匹配非const版本,返回 int
。v2是const 对象,所以v2.begin()匹配const版本,返回 const int*。适用场景:非 const版本用于需要遍历并修改元素的场景;const版本用于只读遍历。
问题4:可以这样写。更新1:std::fill_n(pdata_, n_, value);
功能:从 pdata_ 指向的位置开始,将连续的 n_ 个元素全部赋值为 value。对比:完美替代了原来手写的 for 循环。对于简单类型,它通常能通过编译器优化获得更高的执行效率。更新2:std::copy_n(vi.pdata_, vi.n_, pdata_);
功能:从vi.pdata_指向的位置开始,复制vi.n_个元素,存放到当前对象的pdata_中。对比:替代了原来的for循环拷贝,代码可读性大大提升。更新3:std::copy_n(vi.pdata_, vi.n_, ptr);功能:在assign函数中,分配了新的内存 ptr 之后,将源对象 vi 的数据拷贝到新内存 ptr 中。好处:依然是完美替代了手动 for 循环。在保留原版assign安全逻辑的同时,简化了代码。

任务四

源代码

点击查看代码
matrix.h
#pragma once
#include <iostream>
#include <stdexcept>

class Matrix {
public:
    Matrix(int n_rows, int n_cols, double value = 0);
    Matrix(int n_rows, double value = 0);
    Matrix(const Matrix &x);
    ~Matrix();

    void set(const double *pvalue, int size);
    void clear();

    const double& at(int i, int j) const;
    double& at(int i, int j);

    int rows() const;
    int cols() const;

    void print() const;

private:
    int n_rows_;
    int n_cols_;
    double *pdata_;
};
matrix.cpp
#include "matrix.h"
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <stdexcept>

Matrix::Matrix(int n_rows, int n_cols, double value)
    : n_rows_{n_rows}, n_cols_{n_cols}, pdata_{new double[n_rows*n_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;
    }
}
task4.cpp
#include <cstdlib>
#include <iostream>
#include <stdexcept>

#include "matrix.h"

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

    return 0;
}

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.set(x, n*m);

    Matrix m2(m, n);
    m2.set(x, m*n);

    Matrix m3(n);
    m3.set(x, n*n);

    std::cout << "矩阵m1: \n";    m1.print();
    std::cout << "矩阵m2: \n";    m2.print();
    std::cout << "矩阵m3: \n";    m3.print();
}

void test2() {
    Matrix m1(2, 5, -1);
    const Matrix m2(m1);

    std::cout << "矩阵m1: \n";    m1.print();
    std::cout << "矩阵m2: \n";    m2.print();

    m1.clear();
    m1.at(0, 0) = 1;
    m1.at(0, 1) = 2;

    std::cout << "m1更新后: \n";
    std::cout << "矩阵m1第0行 "; output(m1, 0);
    std::cout << "矩阵m2第0行: "; output(m2, 0);
}

void output(const Matrix &m, int row_index) {
    if(row_index < 0 || row_index >= m.rows())
        throw std::out_of_range("row_index must in [0, m.rows()-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

任务五

源代码

点击查看代码
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_;
};

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 <algorithm>
#include <iostream>
#include <string>
#include <vector>

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

运行结果截图

image

posted @ 2026-11-26 13:15  lp99  阅读(8)  评论(0)    收藏  举报