实验3
实验任务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";
}
点击查看代码
#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;
}
点击查看代码
#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.这个范例中,Window 和 Button 是组合关系吗?
是。Window 类私有成员包含 vector,Button 的生命周期由 Window 管理,符合 “has-a” 组合关系特征。
2.bool has_button(const std::string &label) const; 被设计为私有。 思考并回答:
(1)若将其改为公有接口,有何优点或风险?
暴露内部实现细节,破坏类的封装性同时外部依赖该接口后,后续类内部逻辑修改会
影响外部代码,降低可维护性。
(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 会触发字符串拷贝构造,产生额外内存开销和性能损耗。
在安全性上:接口 1 返回 const 引用,外部无法通过该引用修改私有成员 label,安全性更高;接口 2 返回拷贝值,外部修改拷贝不会影响原对象,但拷贝过程可能带来潜在开销。
4.把代码中所有 xx.push_back(Button(xxx)) 改成 xx.emplace_back(xxx) ,观察程序是否正常运行;查阅资料,回答两种写法的差别。
程序可正常运行。
差别:push_back 接收已构造的 Button 对象,需先创建临时对象再拷贝或移动到 vector;emplace_back 直接接收 Button 构造函数的参数,在 vector 内存中就地构造对象,避免临时对象的创建和拷贝,效率更高。
实验任务2
源代码:
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();
}
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.测试模块1中这两行代码分别完成了什么构造? v1 、v2各包含多少个值为42的数据项?
std::vector
const std::vector
v1 和 v2 均包含 5 个值为 42 的数据项。
2.测试模块2中这两行代码执行后, v1.size() 、v2.size() 、v1[0].size()分别是多少?
std::vector<std::vector
const std::vector<std::vector
v1.size () = 2;
v2.size () = 2;
v1 [0].size () = 3
3.测试模块1中,把 v1.at(0) = -1; 写成 v1[0] = -1; 能否实现同等效果?两种用法有何区别?
能实现同等效果,均修改v1第一个元素的值。
at()会做边界检查,索引越界时抛出out_of_range异常;[]不做边界检查,越界时行为未定义,可能崩溃或破坏内存。
4.测试模块2中执行v1.at(0).push_back(-1); 后
(1)用以下两行代码,能否输出-1?为什么?
std::vector
std::cout<<r.at(r.size()-1);
能输出-1。v1.at (0)返回v1第一个内层vector的引用,push_back(-1)后该vector末尾新增元素-1,r作为引用指向该vector,通过r.size()-1可访问到最后一个元素即-1。
(2)r定义成用const & 类型接收返回值,在内存使用上有何优势?有何限制?
优势:const &接收引用无需拷贝vector,节省内存开销;
限制:const &无法修改所指向的vector,只能用于读取操作。
5. 观察程序运行结果,反向分析、推断:
(1)标准库模板类 vector 的复制构造函数实现的是深复制还是浅复制?
深复制。修改v1的元素后,v2的元素未发生变化,说明v2拥有独立的内存空间,拷贝时复制了所有元素数据。
(2) vector
当 v是vector
当 v是constvector
必须提供const重载版本,否则const vector对象无法调用at()接口,非const版本的at()会允许修改对象,与const对象的只读属性冲突。
实验任务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;
}
点击查看代码
#include "vectorInt.hpp"
#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);
}
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';
}
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';
}
运行截图:

问题回答:
1.当前验证性代码中, vectorInt 接口 assign 实现是安全版本。如果把 assign 实现改成版 本2,逐条指出版本 2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码, 加以分析)
自赋值风险:若传入的vi是对象自身(this == &vi),先执行delete [] ptr会释放自身内存,后续new int [n]后拷贝数据时,vi.ptr已被释放,导致内存非法访问。
内存泄漏风险:若 new int [n] 失败,原 ptr 已被 delete 释放,且未恢复,会导致对象状态异常,ptr成为野指针。
2.当前验证性代码中,重载接口 at 内部代码完全相同。若把非 const 版本改成如下实现, 可消除重复并遵循“最小化接口”原则(未来如需更新接口,只更新const接口,另一个会同步)。
查阅资料,回答:
(1)static_cast<const vectorInt>(this)的作用是什么?转换前后 this 的类型分别是什么?转换目的?
作用:将当前对象的this指针转换为const修饰的vectorInt类型。
转换前this类型:vectorInt(非const);
转换后类型:const vectorInt(const)。
目的:调用const版本的at ()接口,复用其边界检查和元素访问逻辑,避免代码重复。
(2)const_cast<int&> 的作用是什么?转换前后的返回类型分别是什么?转换目的?
作用:移除const修饰符,将const int &转换为int&。
转换前返回类型:const int&(const版本at ()的返回值);
转换后类型:int&(非const)。
目的:在保证非 const 对象可修改的前提下,复用const版本的逻辑,后续仅需维护一个 at ()核心实现。
3. vectorInt类封装了 begin() 和 end() 的const/非const接口。
以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景。
it1调用非const版本(int* begin ())。v1 是普通非const对象,编译器优先匹配非const成员函数,允许通过迭代器修改对象元素。
it2调用const版本(const int* begin () const)。v2 是const对象,只能调用const成员函数,通过迭代器仅能读取元素,无法修改。
非const版本适配可修改的对象,支持通过迭代器修改元素;
const版本适配只读对象(const 对象),仅支持读取元素。
4. 以下两个构造函数及 assign 接口实现,都包含内存块的赋值和复制操作。使用算法库
改写后代码可行。
std::fill_n (ptr, n, value):将ptr指向的连续n个int类型内存空间,全部赋值为value,替代原手动循环赋值。
std::copy_n (vi.ptr, vi.n, ptr):从vi.ptr指向的内存中,拷贝vi.n个int元素到ptr指向的内存空间,替代原手动循环拷贝。
std::copy_n (vi.ptr, vi.n, ptr_tmp):与上一行功能一致,从vi.ptr拷贝vi.n个元素到ptr_tmp 指向的新内存,确保赋值操作的安全性。
实验任务4
源代码如下:
matrix.hpp
点击查看代码
#pragma once
#include <iostream>
#include <algorithm>
#include <cstdlib>
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;
};
点击查看代码
#include "matrix.hpp"
#include <iostream>
#include <cstdlib>
Matrix::Matrix(int rows_, int cols_, double value)
: n_rows(rows_), n_cols(cols_), ptr(new double[rows_ * cols_]) {
if (rows_ <= 0 || cols_ <= 0) {
std::cerr << "Error: rows and cols must be positive\n";
std::exit(1);
}
for (int i = 0; i < rows_ * cols_; ++i) {
ptr[i] = value;
}
}
Matrix::Matrix(int rows_, double value)
: n_rows(rows_), n_cols(rows_), ptr(new double[rows_ * rows_]) {
if (rows_ <= 0) {
std::cerr << "Error: rows must be positive\n";
std::exit(1);
}
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[x.n_rows * x.n_cols]) {
for (int i = 0; i < n_rows * n_cols; ++i) {
ptr[i] = x.ptr[i];
}
}
Matrix::~Matrix() {
delete[] ptr;
}
void Matrix::set(const double *pvalue, int size) {
if (size != n_rows * n_cols) {
std::cerr << "Error: size mismatch\n";
std::exit(1);
}
for (int i = 0; i < size; ++i) {
ptr[i] = pvalue[i];
}
}
void Matrix::clear() {
for (int i = 0; i < n_rows * n_cols; ++i) {
ptr[i] = 0.0;
}
}
const double& Matrix::at(int i, int j) const {
if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
std::cerr << "IndexError: matrix index out of range\n";
std::exit(1);
}
return ptr[i * n_cols + j];
}
double& Matrix::at(int i, int j) {
if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
std::cerr << "IndexError: matrix index out of range\n";
std::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) {
if (j > 0) std::cout << ", ";
std::cout << ptr[i * n_cols + j];
}
std::cout << std::endl;
}
}
点击查看代码
#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";
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;
}
点击查看代码
# 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();
}
// 待补足1:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
int ContactBook::index(const std::string &name) const {
for (size_t i = 0; i < contacts.size(); ++i) {
if (contacts[i].get_name() == name) {
return static_cast<int>(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();
});
}
点击查看代码
#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号