实验3
任务一
- 源代码
bottun.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_;
};
inline 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";
}
点击查看代码
#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();
return 0;
}
点击查看代码
#pragma once
#include "button.hpp"
#include <iostream>
#include <vector>
#include <algorithm>
// 窗口类
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;
std::string title_;
std::vector<Button> buttons_;
};
inline 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;
}
-
代码运行截图
![image]()
-
问题
问题1
Window与Button是组合关系
vector直接保存Button实例,而非指针。
Window对象被创建时,内部vector管理的所有Button同时创建;Window对象被销毁时,vector析构,内部vector管理的所有Button同时自动析构。Button由 Window 管理,Window 拥有 Button,二者生命周期同步。
问题2
1.若将其改为共用接口,优点为外部调用者可以直接判断窗口是否存在某个按钮,外部不用重复写遍历判断逻辑。
2.如果类的外部用户需要调用的功能,对外提供服务,则放在public;
如果仅类内部其他成员函数调用,属于内部实现细节,则放在private。
问题3
性能方面,接口1性能高,不拷贝字符串,直接返回内部成员的别名,没有内存复制开销;接口2会调用 string 拷贝构造,生成新字符串对象;存在内存拷贝开销,字符串越长开销越大。
安全性方面,接口1返回 const 引用,外部不能修改内部 label;接口2返回副本,完全独立于原对象,不存在悬空引用风险。
问题4
1.可以正常运行
push_back(Button(xxx))先在外部构造临时Button对象,再把这个临时对象移动、拷贝到 vector 容器内部。
emplace_back(xxx):直接在 vector 容器的内存空间原位构造Button对象,不需要生成临时对象,直接把参数传给构造函数,减少拷贝、移动,效率更高。
2.可以
参数:first,last`迭代器区间;pred谓词(返回 bool 的可调用对象,lambda / 函数指针)
功能:遍历[first,last)区间,只要任意一个元素满足谓词 pred 返回 true,any_of 就返回 true;全部不满足返回 false。
3.可以
参数:迭代器区间[first,last);谓词 pred
功能:遍历区间,找到第一个满足谓词 pred 的元素,返回该元素的迭代器;全部不满足,返回last尾后迭代器。
任务二
- 源代码
点击查看代码
#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();
return 0;
}
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[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:\n"; output3(v1);
std::cout << "v2:\n"; output3(v2);
v1[0].push_back(-1);
std::cout << "**********修改v1[0]后**********\n";
std::cout << "v1:\n"; output3(v1);
std::cout << "v2:\n"; output3(v2);
}
// 使用索引+循环,遍历输出vector<int>数据项
void output1(const std::vector<int> &v) {
if(v.size() == 0) {
std::cout << '\n';
return;
}
std::cout << v[0];
for(auto i = 1; i < v.size(); ++i)
std::cout << ", " << v[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);
}
-
代码运行截图
![image]()
-
问题
问题1
std::vectorv1(5, 42)完成了构造函数,创建了5个值为42的数据项
const std::vectorv2(v1)完成了复制构造函数,创建了5个值为42的数据项
问题2
v1.size()= 2
v2.size()= 2
v1[0].size()=3
问题3
可以实现同等效果
operator[]是下标运算符:不做越界检查。
at(index)会做下标范围检查
问题4
可以
r是v1[0]的const引用,绑定到原来的子vector对象;push_back修改原vector引用r依然指向这个被修改的对象。
问题5
1.深拷贝
2.当v是vector时,返回值类型是int&;当v是const vetor 时,返回值类型是const int&
必须提供带const修饰的重载版本
任务三
- 源代码
task3.cpp
点击查看代码
#include "vectorInt.hpp"
#include <iostream>
void test1();
void test2();
void test3();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);
int main() {
std::cout << "²âÊÔ1: ¹¹Ôì¡¢¸üÐÂ\n";
test1();
std::cout << "\n²âÊÔ2: const¶ÔÏ󡢸³Öµ\n";
test2();
std::cout << "\n²âÊÔ3: ¸³Öµ\n";
test3();
return 0;
}
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);
y.at(0) = -1;
std::cout << "x: "; output2(x);
std::cout << "y: "; output2(y);
}
void test3() {
vectorInt x(5, 42);
std::cout << "x: "; output2(x);
x.assign(x);
std::cout << "x: "; output2(x);
}
// ʹÓÃ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';
}
点击查看代码
#pragma once
#include <iostream>
#include <stdexcept>
// ¶¯Ì¬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 *pdata_; // Êý¾ÝÇø
};
inline vectorInt::vectorInt():n_{0}, pdata_{nullptr} {
}
inline vectorInt::vectorInt(int n): n_{n}, pdata_{new int[n]} {
}
inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} {
for(auto i = 0; i < n_; ++i)
pdata_[i] = value;
}
inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} {
for(auto i = 0; i < n_; ++i)
pdata_[i] = vi.pdata_[i];
}
inline vectorInt::~vectorInt() {
delete [] pdata_;
}
inline int vectorInt::size() const {
return n_;
}
inline const int& vectorInt::at(int index) const {
if(index < 0 || index >= n_)
throw std::out_of_range("vectorInt::at: index out of range");
return pdata_[index];
}
inline int& vectorInt::at(int index) {
if(index < 0 || index >= n_)
throw std::out_of_range("vectorInt::at: index out of range");
return pdata_[index];
}
inline vectorInt& vectorInt::assign(const vectorInt &vi) {
if(this == &vi)
return *this;
int *ptr;
ptr = new int[vi.n_];
for(int i = 0; i < vi.n_; ++i)
ptr[i] = vi.pdata_[i];
delete[] pdata_;
n_ = vi.n_;
pdata_ = ptr;
return *this;
}
inline int* vectorInt::begin() {
return pdata_;
}
inline int* vectorInt::end() {
return pdata_ + n_;
}
inline const int* vectorInt::begin() const {
return pdata_;
}
inline const int* vectorInt::end() const {
return pdata_ + n_;
}
- 代码运行截图

- 问题
问题1

无异常
没有自赋值判断if(this == &vi)。
当x.assign(x)时,第一步执行delete[] pdata_,释放本对象内存;循环读取已经释放内存,内存访问错误,程序崩溃。
问题2
static_cast<const vectorInt*>(this)作用时把this指针添加const限定,调用const 版本 at (),复用 const at 的边界检查逻辑。转换前是vectorInt *,转换后是const vectorInt *。转换目的是避免重复写一遍边界判断代码,非const版本直接服用const版本逻辑。
const_cast<int&>作用是去除const引用的const限定。转换前是const int &,转换后是int &。转换目的是返回普通引用,允许调用者修改元素;前提是原对象本身不是const对象,这里安全。
问题3
非const对象调用非const版本begin/end;拿到可修改迭代器,可以修改容器元素。
const对象只能调用const版本begin/end,返回const指针,只读,禁止修改容器元素。
任务4
- 源代码
matrix.cpp
点击查看代码
#include "matrix.h"
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
Matrix::Matrix(int n_rows, int n_cols, double value)
: n_rows_{n_rows}, n_cols_{n_cols}, pdata_{new double[n_rows*n_cols]} {
std::fill_n(pdata_, n_rows*n_cols, value);
}
Matrix::Matrix(int n_rows, double value): Matrix(n_rows, n_rows, value) {
}
// ´ýʵÏÖ£º¿½±´¹¹Ô죨É±´£©
Matrix::Matrix(const Matrix &x) {
n_rows_ = x.n_rows_;
n_cols_ = x.n_cols_;
pdata_ = new double[n_rows_ * n_cols_];
std::copy_n(x.pdata_, n_rows_ * n_cols_, pdata_);
}
// ´ýʵÏÖ£ºÊÍ·ÅÖ¸ÕëÖ¸ÏòµÄÄÚ´æ×ÊÔ´
Matrix::~Matrix() {
delete[] pdata_;
}
void Matrix::set(const double *pvalue, int size) {
if(size != n_rows_ * n_cols_)
throw std::invalid_argument("size must match");
std::copy_n(pvalue, size, pdata_);
}
void Matrix::clear() {
std::fill_n(pdata_, 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_)
throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]");
return pdata_[i * n_cols_ + j];
}
// ´ýʵÏÖ£º·µ»Ø¾ØÕó¶ÔÏóË÷Òý(i,j)¶ÔÓ¦µÄÊý¾ÝÏîÒýÓã¨Ô½½çÔòÅ׳öÒì³££©
// ²Î¿¼Ç°Ò»¸ö½Ó¿ÚºÍtask3µÄÎÊÌâ2
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_; ++j)
{
if(j>0) std::cout << ",";
std::cout << at(i,j);
}
std::cout << '\n';
}
}
点击查看代码
#pragma once
// ÀàMatrixÉùÃ÷
class Matrix {
public:
Matrix(int n_rows, int n_cols, double value = 0); // ¹¹Ôìn_rows*n_cols_¾ØÕó¶ÔÏó, ³õÖµvalue
Matrix(int n_rows, double value = 0); // ¹¹Ôìn_rows*n_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 *pdata_; // Êý¾ÝÇø
};
点击查看代码
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#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();
return 0;
}
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, 5, -1);
const Matrix m2(m1);
std::cout << "¾ØÕóm1: \n"; m1.print();
std::cout << "¾ØÕóm2: \n"; m2.print();
m1.clear();
m1.at(0, 0) = 1;
m1.at(0, 1) = 2;
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())
throw std::out_of_range("row_index must in [0, m.rows()-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
- 源代码
contacy.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_; // ±ØÌîÏî
};
inline Contact::Contact(const std::string &name, const std::string &phone):name_{name}, phone_{phone} {
}
inline const std::string& Contact::get_name() const {
return name_;
}
inline const std::string& Contact::get_phone() const {
return phone_;
}
inline void Contact::display() const {
std::cout << name_ << ", " << phone_;
}
点击查看代码
# pragma once
#include "contact.hpp"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
// ͨѶ¼Àà
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; // ·µ»ØÁªÏµÈËÔÚvectorÄÚË÷Òý£¬Èç²»´æÔÚ£¬·µ»Ø-1
void sort(); // °´ÐÕÃû×ÖµäÐòÉýÐòÅÅÐòͨѶ¼
private:
std::vector<Contact> contacts_;
};
inline 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";
}
inline 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";
}
inline 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';
}
inline void ContactBook::display() const {
for(auto &c: contacts_) {
c.display();
std::cout << '\n';
}
}
inline size_t ContactBook::size() const {
return contacts_.size();
}
// ´ý²¹×ã1£ºint index(const std::string &name) const;ʵÏÖ
// ·µ»ØÁªÏµÈËÔÚcontactsÄÚË÷Òý; Èç²»´æÔÚ£¬·µ»Ø-1
inline 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();ʵÏÖ
// °´ÐÕÃû×ÖµäÐòÉýÐòÅÅÐòͨѶ¼
inline 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");
std::cout << "\n5. display contacts\n";
std::cout << "There are " << contactbook.size() << " contacts.\n";
contactbook.display();
}
int main() {
test();
}
- 代码运行截图



浙公网安备 33010602011771号