实验三
实验任务1
代码:
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
#pragma once
#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();
}
运行测试截图:

回答问题:
问题1: 是的
问题2:
(1) 优点:可在外部访问,更灵活;缺点:破坏封装,存在风险;
(2) 看用户是否需要调用、是否为内部实现细节、是否易破坏对象状态——需要且安全的设为 public ,内部细节或易破坏状态的设为 private 。
问题3:
接口1:性能好,无拷贝,安全;接口2:性能较差。
问题4:
程序可正常运行。 push_back 需先构造对象再拷贝并移动; emplace_back 直接在容器内构造对象,更高效。
实验任务2
代码:
task.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);
}
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';
}
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';
}
void output3(const std::vector<std::vector<int>>& v) {
if (v.size() == 0) {
std::cout << '\n';
return;
}
for (auto& i : v)
output2(i);
}
运行测试截图:

回答问题:
问题1:
第一行代码: std::vector
数据项数量: v1 和 v2 各包含5个值为42的数
问题2:
v1.size() :2; v2.size() :2。
v1[0].size() :3; v2[0].size() :3。
问题3:
能实现同等效果。
区别: at(0) 会进行边界检查,若索引越界会抛出 out_of_range 异常; v1[0] 不进行边界检查,索引越界时行为未定义。
问题4:
(1)不能输出。因为 v1.at(0).size() 是3, r.at(2) 是3。
(2)优势:使用 const & 接收返回值避免了对象拷贝,节省内存和时间;限制:无法通过该引用修改原对象内容。
问题5:
(1)标准库模板类 vector 的复制构造函数实现的是深复制。因为修改原 vector 的元素后,拷贝得到的 vector 元素不会改变,说明两者内存独立。
(2)当 v 是 vector
实验任务3
代码:
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;
}
运行测试截图:

回答问题:
问题1:
安全隐患:版本2的 assign 中先 delete[] ptr 再分配新内存,若 new int[n] 失败(如内存不足),会导致 ptr 悬空。
版本2未处理自赋值( this == &vi ),若自赋值会因先 delete 旧内存导致数据丢失。
问题2:
(1):
作用:将 this 指针从 vectorInt* 转换为 const vectorInt* ,明确调用 const 版本的 at() 。
类型:转换前 this 是 vectorInt* ,转换后是 const vectorInt* 。
目的:确保调用 const 版本的 at() 接口,实现代码复用。
(2):
作用:将 const int& 转换为 int& ,去除 const 属性。
类型:转换前返回类型是 const int& ,转换后是 int& 。
目的:使非 const 版本的 at() 能返回可修改的引用,同时复用 const 版本的实现,遵循“最小化复制”原则。
问题3:
(1):
auto it1 = v1.begin(); 调用非const版本的 begin() ,适配需要修改容器元素的场景。
auto it2 = v2.begin(); 调用const版本的 begin() ,适配仅读取容器元素的场景。
(2):
迭代器可基于指针实现,其核心作用是提供统一的元素遍历接口,即使底层是指针,也能通过迭代器抽象屏蔽实现细节,让遍历逻辑更通用、安全。
问题4:
可以

std::fill_n(ptr, n, value) :将 ptr 指向的内存块中连续 n 个元素赋值为 value ,实现批量初始化。
std::copy_n(vi.ptr, vi.n, ptr) :从 vi.ptr 开始,复制连续 vi.n 个元素到 ptr 指向的内存块,实现深拷贝。
std::copy_n(vi.ptr, vi.n, ptr_tmp) :从 vi.ptr 开始,复制连续 vi.n 个元素到 ptr_tmp 指向的内存块,为 assign 接口实现深拷贝逻辑。
实验任务4
代码:
matrix.hpp
#pragma once
class Matrix {
public:
Matrix(int rows_, int cols_, double value = 0);
Matrix(int 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* ptr;
};
Matrix::Matrix(int rows_, int cols_, double value) :n_rows{ rows_ }, n_cols{ cols_ }, ptr{ new double[n_cols * n_rows] } {
for (int i = 0; i < n_rows; i++)
for (int j = 0; j < n_cols; j++)
ptr[i * n_cols + j] = value;
}
Matrix::Matrix(int rows_, double value ) :n_rows{ rows_ },n_cols { rows_ }, ptr{ new double[n_cols * n_rows] } {
for (int i = 0; i < n_rows; i++)
for (int j = 0; j < n_rows; j++)
ptr[i * n_rows + j] = value;
}
Matrix::Matrix(const Matrix& x) :n_rows{ x.n_rows }, n_cols{ x.n_cols }, ptr{ new double[n_cols * n_rows] } {
for (int i = 0; i < n_rows; i++)
for (int j = 0; j < n_cols; j++)
ptr[i * n_cols + j] = x.ptr[i * n_cols + j];
}
Matrix::~Matrix() {
delete[] ptr;
}
void Matrix::set(const double* pvalue, int size) {
if (n_rows * n_cols != size) return ;
for (int i = 0; i < n_rows; i++)
{
for (int j = 0; j < n_cols; j++)
{
ptr[i * n_cols + j] = pvalue[i * n_cols + j];
}
}
}
void Matrix::clear() {
for (int i = 0; i < n_rows; i++)
{
for (int j = 0; j < n_cols; j++)
{
ptr[i * n_cols + j] = 0;
}
}
}
const double& Matrix::at(int i, int j) const {
if (i<0 || i>n_rows||j<0 || j>n_cols) std::exit(1);
return ptr[i * n_cols + j];
}
double& Matrix::at(int i, int j) {
return const_cast<double&>(static_cast<const Matrix*>(this)->at(i,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++)
{
std::cout << ptr[i * n_cols];
for (int j = 1; j < n_cols; j++)
{
std::cout << ',' << ptr[i * n_cols + j];
}
std::cout << std::endl;
}
}
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.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, 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);
}
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::cout << '\n';
}
运行测试截图:

实验任务5
代码:
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;
}
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;
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();
}
int ContactBook::index(const std::string& name) const {
int num = -1;
for (auto& m : contacts)
{
num++;
if (name == m.get_name()) return num;
}
return num;
}
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");
}
int main() {
test();
}
运行测试截图:


浙公网安备 33010602011771号