【发布时间】:2021-01-01 15:14:50
【问题描述】:
我有这个代码:
struct PointComparator
{
explicit PointComparator(const Point& lowest)
: m_lowest(lowest)
{}
bool operator()(const Point& a, const Point& b)
{
std::cout << m_lowest[0] << std::endl;
return; // TODO
}
private:
Point m_lowest;
};
// in another function:
Point lowestPoint; // (get this from somewhere)
std::sort(points.begin(), points.end(), PointComparator(lowestPoint));
我只是对显式关键字感到困惑。当我做一个正常的排序时,我会调用类似sort(sort(points.begin(), points.end(), compar())的东西,而compar()指向bool operator()(const Point& a, const Point& b)函数,但现在PointComparator(lowestPoint)指的是构造函数,那么它是如何工作的呢?
【问题讨论】:
-
它不是“引用构造函数”,它只是构造一个匿名对象,恰好使用了您编写的单参数构造函数。有什么特别令人困惑的?为什么你认为
explicit会让人更加困惑?
标签: c++ struct constructor operator-overloading comparator