实验3

Task1

代码

Button.h
#pragma once

#include <iostream>
#include <string>

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

private:
	std::string label;
};

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

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

Window.h
#pragma once

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

#include "Button.h"

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

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_lab() << 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_lab() == 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_lab() == label) {
			button.click();
			return;
		}
	std::cout << "no button: " << label << std::endl;
}
Button.cpp
#include "Button.h"

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

}


Window.cpp

task1.cpp
#include "Window.h"
#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();
}

运行截图

task1

问题

问题1:这个范例中, Window 和 Button 是组合关系吗?

Window 和 Button是组合关系
原因:Button对象是Window的私有成员,即Button的存在依赖于Window的存在

问题2:bool has_button(const std::string &label) const; 被设计为私有。 思考并回答:
(1)若将其改为公有接口,有何优点或风险?

优点:能够直接从外部进行访问has_button()函数,增强代码可读性
缺点:暴露了其内部实现细节,违反了封装原则

(2)设计类时,如何判断一个成员函数应为 public 还是 private?(可从“用户是否需要”、“是否仅为内部实现
细节”、“是否易破坏对象状态”等角度分析。)

public部分的成员函数是给用户所使用,满足用户的需求,不会破坏对象的一致性
private部分的成员函数不给用户直接调用,以减少理解成本(不需要用户去理解内部细节),且避免了外部干扰对象状态

问题3:Button 的接口 const std::string& get_label() const; 返回 const std::string& 。对比以下
两种接口设计在性能和安全性方面的差异并精炼陈述。
接口1: const std::string& get_label() const;
接口2: const std::string get_label() const;

接口1:无需进行拷贝操作,减少内存消耗。可能破坏对象内部状态,安全性上存在一定的风险
接口2:需要进行拷贝操作,需要额外内存。不会修改对象内部的原始字符串,安全性能高

问题4:把代码中所有 xx.push_back(Button(xxx)) 改成 xx.emplace_back(xxx) ,观察程序是否正常运
行;查阅资料,回答两种写法的差别。

可以正常运行。
push_back()先构造临时对象,再进行移动或拷贝构造函数
emplace_back()直接创造Button对象,效率更高

Task2

代码

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

//验证vector<int>的深复制
//拷贝后未修改原容器,仅展示拷贝结果
void test1() {
	std::vector<int> v1(5, 42);	//v1:42,42,42,42,42
	const std::vector<int> v2(v1);

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

//验证vector<vector<int>>的深复制
//拷贝后修改原容器的子vector,观察拷贝容器是否受影响
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>数据项
//v.at(i)—— 安全的元素访问方式(越界时会抛出out_of_range异常,比v[i]更安全)
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;
	}

	//*it:解引用迭代器,获取它指向的元素值
	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>>数据项
// 参数类型vector<vector<int>>:二维容器(容器的每个元素也是一个vector<int>)
void output3(const std::vector<std::vector<int>>& v) {
	if (v.size() == 0) {
		std::cout << '\n';
		return;
	}
// 范围 for 循环for (auto& i : v):遍历二维容器的每个元素(即每个子vector<int>)
// 用auto&而非auto:避免拷贝子vector,提高效率(auto会触发子容器的拷贝构造,没必要)
	for (auto& i : v)
		output2(i);
}

运行截图

task2

问题

问题1:测试模块1中这两行代码分别完成了什么构造? v1 、 v2 各包含多少个值为 42 的数据项?

构造函数和拷贝构造函数 v1和v2各包含5个42

问题2:测试模块2中这两行代码执行后, v1.size() 、 v2.size() 、 v1[0].size() 分别是多少?

2,2,3

问题3:测试模块1中,把 v1.at(0) = -1; 写成 v1[0] = -1; 能否实现同等效果?两种用法有何区别?

能实现相同的效果
v1.at(0) = -1使用时更加安全;v1[0] = -1使用时存在安全风险,但是性能更好

问题4:测试模块2中执行 v1.at(0).push_back(-1); 后
(1) 用以下两行代码,能否输出-1?为什么?
(2)r定义成用 const & 类型接收返回值,在内存使用上有何优势?有何限制?

(1)能输出,r引用的对象是v1.at(0),两者使用的内存空间相同。
(2)节省空间,限制就是不能修改

问题5:观察程序运行结果,反向分析、推断:
(1) 标准库模板类 vector 的复制构造函数实现的是深复制还是浅复制?
(2) vector::at() 接口思考: 当 v 是 vector 时, v.at(0) 返回值类型是什么?当 v 是 const
vector 时, v.at(0) 返回值类型又是什么?据此推断 at() 是否必须提供带 const 修饰的重载版本?

(1)深复制
(2)当 v 是 vector<int> 时, v.at(0) 返回值类型是int &;
	当 v 是 const vector<int> 时, v.at(0) 返回值类型是const int &;
	是

Task3

代码

VectorInt.h
#pragma once

#include <iostream>

//动态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* ptr;	//数据区
};


VectorInt.cpp
#include "VectorInt.h"

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.h"

#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);
}

// 使用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';
}

运行截图

task3

问题

问题1:当前验证性代码中, vectorInt 接口 assign 实现是安全版本。如果把 assign 实现改成版本2,逐条指
出版本 2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码,加以分析)

版本2缺少自赋值检查,可能会造成对象状态异常

问题2:当前验证性代码中,重载接口 at 内部代码完全相同。若把非 const 版本改成如下实现,可消除重复并
遵循“最小化接口”原则(未来如需更新接口,只更新const接口,另一个会同步)。
(1) static_cast<const vectorInt*>(this) 的作用是什么?转换前后 this 的类型分别是什么?转换目
的?

类型转换
前: VectorInt* ,后: const VectorInt*
调用const int& at(int index) const函数,实现代码复用

(2) const_cast<int&> 的作用是什么?转换前后的返回类型分别是什么?转换目的?

移除const限制
前:const int & , 后: int &
移除const限定符,实现了代码复用

问题3: vectorInt 类封装了 begin() 和 end() 的const/非const接口。
(1)以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景

v1调用了非const版本,v2调用了const版本。
const主要是对数据进行访问操作,不对数据进行修改,适合用于保护数据
非const主要是对数据进行修改

(2)拓展思考(选答*):标准库迭代器本质上是指针的封装。 vectorInt 直接返回原始指针作为迭代器,这
种设计让你对迭代器有什么新的理解?

迭代器是对指针的封装,调用时其实是调用指针。

问题4:以下两个构造函数及 assign 接口实现,都包含内存块的赋值和复制操作。使用算法库
成如下写法是否可以?回答这3行更新代码的功能。

可以
第一个更新代码:从指针指向的地址开始,用n个value依次填充
第二个和第三个更新代码:将容器vi.ptr的vi.n个元素依次复制到容器ptr_tmp中

Task4

代码

Matrix.h
#pragma once

class Matrix
{
public:
	//构造rows_*cols_矩阵对象,初始value=0
	Matrix(int rows_, int cols_, double value = 0);	
	//构造rows_*rows_方阵对象,初始value=0
	Matrix(int rows_, double value = 0);	
	//深复制
	Matrix(const Matrix& x);
	~Matrix();

	//按行复制pvalue指向的数据,要求size = rows*cols,否则报错退出
	void set(const double* pvalue, int size);
	//矩阵对象数据项置0
	void clear();

	// 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
	const double& at(int i, int j) const;
	// 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
	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.cpp
#include "Matrix.h"

#include <iostream>

//构造rows_*cols_矩阵对象,初始value=0
Matrix::Matrix(int rows_, int cols_, double value) :n_rows{ rows_ }, n_cols{ cols_ } {
	if (rows_ <= 0 || cols_ <= 0) {
		std::cout << "错误:行数或列数必须为正整数!" << std::endl;
		exit(1);
	}
	ptr = new double[n_rows * n_cols];
	for (int i = 0; i < rows_ * cols_; ++i) {
		ptr[i] = value;
	}
}
//构造rows_*rows_方阵对象,初始value=0
Matrix::Matrix(int rows_, double value) :n_rows{ rows_ }, n_cols{ rows_ } {
	if (rows_ <= 0) {
		std::cout << "错误:行数或列数必须为正整数!" << std::endl;
		exit(1);
	}

	ptr = new double[rows_ * rows_];
	for (int i = 0; i < rows_ * rows_; ++i) {
		ptr[i] = value;
	}
}
//深复制
Matrix::Matrix(const Matrix& x) :n_rows{ x.n_rows }, n_cols{ x.n_cols } {
	ptr = new double[n_rows * n_cols];
	for (int i = 0; i < n_rows * n_cols; ++i) {
		ptr[i] = x.ptr[i];
	}
}
Matrix::~Matrix() {}

//按行复制pvalue指向的数据,要求size = rows*cols,否则报错退出
void Matrix::set(const double* pvalue, int size) {
	if(size != n_rows * n_cols){
		std::cout << "错误:矩阵大小有误!" << std::endl;
		exit(1);
	}

	std::copy(pvalue, pvalue + size, ptr);
}
//矩阵对象数据项置0
void Matrix::clear() {
	std::fill_n(ptr, n_rows * n_cols, 0);
}

// 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
const double& Matrix::at(int i, int j) const {
	if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
		std::cout << "错误:越界!" << std::endl;
		exit(1);
	}

	return ptr[i * n_cols + j];
}
// 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
double& Matrix::at(int i, int j){
	if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
		std::cout << "错误:越界!" << std::endl;
		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) << " ";
		std::cout << std::endl;
	}
}


task4.cpp
#include <iostream>
#include <cstdlib>

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

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

运行截图

task4

Task5

代码

Contact.h
#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; // 必填项
};

ContactBook.h
#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

#include "Contact.h"

// 通讯录类
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;
};

Contact.cpp
#include "Contact.h"

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.cpp
#include "ContactBook.h"

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

// 实现返回联系人在contacts内索引; 如不存在,返回-1
int ContactBook::index(const std::string& name) const{
	for (auto i = 0; i < contacts.size(); ++i) {
		if (contacts[i].get_name() == name) {
			return static_cast<int>(i); 
		}
	}
	return -1; 
}

// 实现按姓名字典序升序排序通讯录
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.h"

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

运行截图

task5

posted @ 2025-11-23 16:31  永和九年2  阅读(7)  评论(0)    收藏  举报