【发布时间】:2021-01-15 09:18:21
【问题描述】:
问题
假设我们有一个简单的类来对整数列表进行排序,
class Sorter {
public:
Sorter() {}
~Sorter() {}
enum class Algorithm { Bubble, Heap, Merge, Insertion };
void SetVector(const std::vector<int>& vec) { mVector = vec; }
void Sort(Algorithm algo)
{
void (Sorter:: * pfSort)() = nullptr;
switch (algo)
{
case Sorter::Algorithm::Bubble:
pfSort = &Sorter::BubbleSort;
break;
case Sorter::Algorithm::Heap:
pfSort = &Sorter::HeapSort;
break;
case Sorter::Algorithm::Merge:
pfSort = &Sorter::MergeSort;
break;
case Sorter::Algorithm::Insertion:
pfSort = &Sorter::InsertionSort;
break;
default:
std::cerr << "Invalid or Unsupported Sort Algorithm!";
break;
}
(this->*(pfSort))();
}
private:
void BubbleSort() { ... }
void HeapSort() { ... }
void MergeSort() { ... }
void InsertionSort() { ... }
private:
std::vector<int> mVector;
};
正如您所看到的,何时进行排序,我们要求使用特定的算法,并根据它,将函数分配给函数指针,最后我们将其称为搜索。
但问题是,为什么我们这样调用函数指针:(this->*(pfSort))(); 而不是这样:pfSort()?
【问题讨论】:
标签: c++ function-pointers