接下来, 准备archive每天实际编程中遇到的C++问题,解决问题的过程, 以及得到的结果。以此来熟悉C++的各种特性。
这样做或许会造成知识点离散, 因此, 后续有必要有选择的,对某些特性进行深入剖析。先破破的来吧,以致于我不会从一个细节陷阱中出来,又陷入另一个。
右移,左移
_capacity >>= 1; // _capacity *= 0.5; |
new delete
要先new一个新的, 才能delete旧的
template <typename T> |
new分配空间
void copyFrom(T* tarr, int lo, int hi) { |
void copyFrom(T* tarr, int lo, int hi) { |
为什么一定要为_elem分配空间? 内存回收问题。 在C++ Primer中具体学习
同一if语句, 同一行中的后置递增
void f() { |
同一if, for, while语句中, 后置递增返回当前值
同一行, 不同语句, 当然会让值产生变化
重载后置++操作符号
前置递增 operator++()
后置递增, 以前置递增为基础 operator++(int i)
increment_and_decrement_operators.cpp
递增运算符重载的返回类型:为什么返回*_elem 而不是 *this??
递减运算符重载函数的返回类型是int&
*this的类型为Vector
template <typename T> |
<<C++ Primer 5th>> P502, P421
函数指针 和 函数对象
对无序向量的遍历操作中, 统一对各个元素分别实施visit操作
函数指针, 只读或者局部性修改
template <typename T> |
函数对象, 可全局性修改
template <typename T> <template VST> |
函数指针
int getLarger(const int& i1, const int& i2) { |
声明定义
声明和定义分离:
int (*pf1)(const int&, const int&); |
个人认为&表达出pf1是个指针的语义明确点。
声明并定义:
int (*pf1)(const int&, const int&) = &getLarger; |
使用
使用
int i_pf1 = (*pf1)(3, 5); |
赋值, 指向新的函数?
bool compareInt(const int& i1, const int& i2) { |
能重新指向一个nullptr或0, 但是不能指向一个与声明类型不同的新函数地址。
但如果是一个类型相同的函数, 便可以重新指向该函数。
bool otherCompare(const int& i1, const int&) {return 0;} |
重载函数的指针
函数指针 指向重载函数, 需要在声明时, 形参列表和返回类型需要完全匹配
void ff(int*); |
函数指针作为形参(调用函数指针)
// 第三个参数是函数指针类型 |
可以用别名的方法简化定义
typedef decltype(compareInt) *FuncP2; // FuncP2是指向函数的指针类型 |
返回指向函数的指针
一般, 别名
using PF = bool(*)(const int&, const int&); // PF是函数的指针类型 |
尾置
auto f1(int) -> int(*)(int*, int) |
函数对象
重载()
说明这个对象, 他可以当作函数来使用。因此需要重载”()”
// 定义一个函数对象 |
使用这个函数对象
Sum s; |
作为其他函数的参数
// 函数对象作为另一个函数的形参 |
回顾一下数据结构中的用法
template <typename T> template <typename VST> |
/* my error test |