实验3 类和对象_基础编程2
实验任务1
代码组织:
button.hpp Button类定义
window.hpp Window类定义
task1.cpp 测试模块、main
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:window和button类是组合关系,因为在window类中定义并使用了button类的对象及其方法。
问题2(1):将函数has_button()设为公有接口,能在buttons容量较大时比人工调用display()更精准的判定某个功能按键是否存在,但该函数不应该被开放给图形界面用户调用,定义时使用了inline其关键字功能是内联,但在语义上表明了该函数只是某个功能函数的可优化模块,而并非一个开放给用户使用的完整功能函数。
(2)判断一个成员函数应为public还是private,最主要的判定方式是用户是否需要使用这个接口,需要就开放,否则不开放,以此来维护类封装的安全性,在者就是封装应该隐藏函数的实现,对于参数过多的功能函数,应该设为private,在设一个参数较少的public成员函数来调用这个功能函数,以此来保证实现的隐藏。
问题3:使用接口1返回对象的引用更快速,从函数返回值上来看,类对象和结构体变量一样,大小通常远大于一般数据类型,直接返回值会很慢,而且传值会隐式调用拷贝构造函数,造成难以调试语义的问题,而传引用会尝试隐式调用移动构造函数,更安全。
问题4:修改后程序正常运行,输出结果与修改前相同,Ctrl+Click检查头文件中的实现,发现xx.push_back(Button(xxx)),的实现就是调用xx.emplace_back(xxx),将Button对象作为移动构造参数传给内部的emplace_back()函数,单纯从实现上来看,两者应该没有区别,但push_back()在传值时的确额外多创建了一个对象,所以直接调用xx.emplace_back(xxx)会更快速。
实验任务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);
}
// 使用xx.at()+循环输出vector<int>数据项
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;
}
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);
}
运行测试结果如下:

问题1:测试模块1中的std::vector<int> v1(5, 42);完成了填充构造,const std::vector<int> v2(v1);完成了拷贝构造,v1和v2两个对象中各包含5个值为42的元素。
问题2:v1使用填充构造,v1.size() = 2,v2使用拷贝构造,v2.size() = 2,v1[0]使用填充构造,v1[0].size() = 3。
问题3:效果几乎相同,但xx.at(xxx)会先检查下标是否越界,而xx[xxx]下标索引则不会。
问题4(1):能输出,v1中的元素本身是vector<int>类型的,可以使用xx.push_back(xxx)合法的在容器尾部插入元素,元素也能被正常引用。
(2)函数返回引用给引用变量r不会进行拷贝构造,所以对于对象这种大型变量来说会非常快,但如果函数返回的对象在函数退出时被销毁,引用r就会悬空,考虑到是const &类型,则此时该变量在整个生命周期中都无法使用。
问题5(1):因为由v1拷贝构造的v2在v1修改后没有变化,所以标准库的拷贝构造实现应该是深拷贝。
(2)不必提供带const的at()函数重载副本,对于vector<int>型的对象,返回的是int型的基础数据类型的值,不涉及引用的传递,所以此处的const限制意义不大,不必重载。
实验任务3
代码组织:
vectorInt.hpp vectorInt类定义
task3.cpp 普通函数、测试模块、main
vectorInt.hpp
#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::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.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()+循环输出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';
}
运行测试结果如下:

问题1:1)缺少卫语句,无法处理自赋值的情况,自赋值会导致数据丢失和使用已经释放的内存块。2)直接将申请的新内存块赋给对象的成员指针,如果申请内存异常导致赋值意外退出,则this->ptr处于已被释放的状态,无论是再次赋值还是析构都会导致双重释放问题.3)在资源转移时使用ptr[i] = v1.ptr[i];容易造成语义上的混淆,不利于维护代码的可读性。
问题2(1):static_cast是在编译期执行编译器确保安全的强制转换的关键字,将当前处理的对象的this指针强制转换为const类型,此时就可以调用返回值为const &的at()成员函数了。
(2):const_cast关键字能破坏变量的const关键字限制,将其转换为非const变量,将上一小问提到的at()函数返回值转化为非const类型再返回退出函数,整个过程通过缩小增加限制再特殊处理不同的返回值将const和非const返回值的at()函数的实现统一了。
问题3(1):v1使用非const接口,v2使用const接口,编译器优先使用与变量类型匹配的const/非const接口。
(2):迭代器也可以像指针一样通过+运算符后移,通过-运算符前移,通过*运算符解引用。
问题4:关于使用标准库更新的部分:1)标准库fill_n()函数将指定的值安全的填充到新对象的内存块,同时可以防止内存越界访问,且比循环更快。2)标准库copy_n()函数将用于拷贝的对象内存块内的数据安全的复制到新对象内存块,同时可以防止内存越界访问,且比循环更快。3)标准库copy_n()函数将赋值内存块内的数据安全的复制到辅助变量指向的内存块,同时可以防止内存越界访问,且比循环更快。
实验任务4
代码组织:
martix.hpp Martix类声明
matrix.cpp Martix类实现
task4.cpp 测试代码 main
martix.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; // 数据区
};
martix.cpp
```c++
#include "matrix.hpp"
#include <iostream>
#include <algorithm>
Matrix::Matrix(int rows_, int cols_, double value): n_rows(rows_), n_cols(cols_), ptr(new double[rows_ * cols_]) {
std::fill_n(ptr, rows_ * cols_, value);
}
Matrix::Matrix(int rows_, double value): n_rows(rows_), n_cols(rows_), ptr(new double[rows_ * rows_]) {
std::fill_n(ptr, rows_ * 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 << "SizeError: size not match the matrix\n";
std::exit(1);
}
std::copy_n(pvalue, size, ptr);
}
void Matrix::clear() {
std::fill_n(ptr, 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) {
std::cerr << "IndexError: i or j out of range\n";
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) {
for (int j = 0; j < n_cols - 1; ++j) {
std::cout << ptr[i * n_cols + j] << ", ";
}
std::cout << ptr[(i + 1) * n_cols - 1] << '\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 Contact类定义
contactBook.hpp ContactBook类定义
task5.cpp 测试代码 main
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();
}
int ContactBook::index(const std::string &name) const {
for (int i = 0; i < contacts.size(); ++i) {
if (contacts[i].get_name() == name) {
return i;
}
}
return -1;
}
// 返回联系人在contacts内索引; 如不存在,返回-1
void ContactBook::sort() {
std::sort(contacts.begin(), contacts.end(), [](Contact a, Contact b) {return a.get_name() < b.get_name();});
}
// 按姓名字典序升序排序通讯录
运行测试结果如下:

实验总结:
C++中的类class是一个非常强大的工具,自动生成的构造函数和析构函数让对象的创建与销毁像基本数据类型一样自动维护,用户可以更加专注与功能的实现,但这同样也是一个危险的陷阱,构造函数和析构函数的处理如上文所述,是与基本数据类型相似的,这意味着自动生成的构造与析构函数无法处理需要动态分配内存的情况,此时就需要手动设计构造函数和析构函数,但也不必全部推倒重来,基本数据类型的成员仍可以用自动化的部分操作,用户只要专心设计动态分配的部分即可,在设计构造函数与功能函数时,要注意浅拷贝与异常处理,不要让析构函数以外的函数在正常或异常的状况下返回一个未被析构但已经释放动态分配内存的对象,这会导致双重释放,总之,永远不要在析构对象前,让对象的指针成员指向一片被释放的内存。
再次体会到标准库提供的巨大便利,几乎所有设计类实验的实现部分都能在标准库中找到方案,标准库中的函数意味着正确,安全与便利,同样的,标准库实现也有利于面向对象,使得用户更加注重与功能的设计而非某个细节实现的边界条件打磨与安全性异常处理。

浙公网安备 33010602011771号