实验3_CPP
任务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.emplace_back("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.emplace_back(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;
}
task_1.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
window和button是组合关系,button以动态数组的形式组合在window类中。
问题2
(1)has_button若被设为公有接口,用户可以直接调用,优点是用户在新增按钮前,可以提前查看一个按钮标签是否已经存在;缺点是has_button函数在任何地方都可被调用,外部代码会依赖这个方法,后续如果要修改这个方法,则需要考虑所有外部依赖的兼容性,维护成本很高。
(2)一个类中需要对用户开放的接口应被设为公有,如果一些方法和临时数据仅需要被内部调用,或涉及修改对象状态时,应该设为私有,防止用户误操作导致系统故障或被恶意入侵。
问题3
接口1:const std::string& get_lable() const; 接口2:const std::string get_label() const;
性能方面:接口1返回的是已有string对象的引用,不需要创建新对象,性能较高;接口2返回的是一个临时string对象,需要创建新对象并将原有对象的值复制到新对象中,性能较低。
安全性方面:接口1返回的是引用类型,如果被引用的对象被销毁,后续再使用这个引用会导致报错,安全性较低;接口2返回的是临时对象,生命周期由调用方决定,原对象被销毁不影响后续调用。
问题4
程序可以正常运行。push_back()在传入通过参数构造的对象时,需要创建一个临时对象,再优先尝试通过移动构造将其加入vector对象,如果元素类型无可用的移动构造函数,则会使用复制构造;而emplace_back()可以直接接收参数,在容器内直接调用构造函数,不需要创建临时对象,性能更高。
任务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 << "deep copy test1: 标准库vector<int>\n";
test1();
std::cout << "\ndeep copy test2: 标准库vector<int>嵌套使用\n";
test2();
}
void test1()
{
std::vector<int> v1(5, 42);
const std::vector<int> v2(v1);
std::cout << "after copy constructure:";
std::cout << "v1 : "; output1(v1);
std::cout << "v2 : "; output1(v2);
v1.at(0) = -1;
std::cout << "after modify v1[0]";
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 << "after copy constructure:";
std::cout << "v1 : "; output3(v1);
std::cout << "v2 : "; output3(v2);
v1.at(0).push_back(-1);
std::cout << "after modify v1[0]";
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
问题2
v1.size() = 2,v2.size() = 2, v1[0].size() = 3
问题3
能实现等同效果,v1[0]不做任何边界检查,如果索引超出范围,会非法访问内存,触发未定义行为;at()成员函数会先检查索引是否有效,可避免非法访问内存,更安全。
问题4
(1)
可以输出-1,r.size()-1 = 3, 值-1的下标是3,可以访问。
(2)
const &类型返回值返回的是不可修改的引用类型,可以避免创建临时对象,节省内存空间;如果被引用的现有对象被销毁,再次调用时会出现未定义问题。
问题5
(1)
vector的默认复制构造函数实现的是深复制。
(2)
v=vector
任务3
源代码
vectorInt.hpp
#pragma once
#include <iostream>
#include <algorithm>
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;
std::fill_n(ptr, n, 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];
std::copy_n(vi.ptr, vi.n, ptr); // 更新
}
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)
{
return const_cast<int&>(static_cast<const vectorInt*>(this)->at(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];
std::copy_n(vi.ptr, vi.n, ptr_tmp); // 更新
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.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);
}
// 使用xx.at()+循环输出
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
当尝试用自身给自身赋值时,原代码会在最前做一次判断,可以避免原数据被释放;版本2中直接释放原数据,如果赋值给自身则会导致数据被异常释放,ptr成为野指针。
如果使用new[]分配内存失败报错时,原代码使用临时指针变量来指向分配内存,失败时不会影响到原数据;版本2中将原数有据释放后使用自身的ptr指针来指向分配的内存,如果分配失败,原有数据无法找回,ptr为野指针,安全性较低。
问题2
(1)
static_cast<const vectorInt>(this)的作用是将this指针的类型强制转换为const vectorInt,转换前this指针的类型是vectorInt,转换后是const vectorInt。目的是让this能调用有const版本的at()函数。
(2)
const_cast<int&>()的作用是移除()中引用的const属性,转换前返回类型是const int&,转换后返回类型是int&。目的是将const版本的at()的返回值类型转换以适配当前函数需要返回的int&类型。
问题3
(1)
编译器会优先选择匹配最完全的重载函数。当const vectorInt类型或通过const指针、引用调用begin()时,选用const版本的begin();当非const类型或通过非const指针、引用调用begin()时,选用非const版本的begin()。
问题4
可以改写。std::fill(ptr,n,value)的功能是将从ptr为起始的n个元素赋值为value;std::copy_n的功能是将从vi.ptr为起始的vi.n个元素复制到以ptr为起始的容器中。
第一处更新是将vectorInt对象中的数据批量赋值,第二处更新是将vi中的数据批量复制到新的对象中,第三处更新是将临时存储的数据批量赋值到原先的对象中。
任务4
源代码
matrix.hpp
#pragma once
#include <iostream>
#include <algorithm>
#include <cstdlib>
// 类Matrix声明
class Matrix {
public:
Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value
Matrix(int rows_, double value = 0); // 构造rows_*rows_方阵对象, 初值value
Matrix(const Matrix &x); // 深复制
~Matrix();
void set(const double *pvalue, int size); // 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出
void clear(); // 矩阵对象数据项置0
const double& at(int i, int j) const; // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
double& at(int i, int j); // 返回矩阵对象索引(i,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[rows_ * cols_] }
{
std::fill_n(ptr, n_rows * n_cols, value);
}
Matrix::Matrix(int rows_, double value) : n_rows{ rows_ }, n_cols{ rows_ }, ptr{ new double[rows_ * rows_] }
{
std::fill_n(ptr, n_rows * n_rows, 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] }
{
std::copy_n(x.ptr, x.n_rows * x.n_cols, ptr);
}
Matrix::~Matrix()
{
delete[] ptr;
}
void Matrix::set(const double* pvalue, int size)
{
if (n_rows * n_cols != size)
{
std::cerr << "Set Size Not Fit Matrix Size";
return;
}
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;
}
const double& Matrix::at(int i, int j) const
{
if (i < 0 || j < 0 || i >= n_rows || j >= n_cols)
{
std::cerr << "Const At Not Fit Matrix Size";
;
}
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
{
if (n_rows == 0 || n_cols == 0)
{
std::cout << '\n';
return;
}
for (int i = 0; i < n_rows; i++)
{
int j = 0;
std::cout << ptr[i * n_cols];
for (j = 1; j < n_cols; j++)
{
std::cout << ", " << ptr[i * n_cols + j];
}
std::cout << '\n';
}
}
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, 大小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";
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; // 返回联系人在contacts内索引,如不存在,返回-1
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.at(i).get_name() == name)
return i;
}
return -1;
}
// 已补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
void ContactBook::sort()
{
int n = contacts.size();
for (size_t i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (contacts.at(j).get_name() > contacts.at(j+1).get_name())
std::swap(contacts.at(j), contacts.at(j + 1));
}
}
}
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号