是否有一些使用Object::*的实际示例

Are there some practical examples that use Object::*

本文关键字:Object 是否      更新时间:2023-10-16

我刚刚听说有一种类型像这样,一个指向对象的成员。这是

class Point{float x, y;};
float Point::*p2 = &Point::x; 

但我以前没有用过,不知道有人真的用过。你有这样的经验吗?

如果您想在不重复代码的情况下对成员应用相同的处理方法,这将非常有用。

vector<Point> points; // suppose it has many elements
vector<double> Project(const vector<Point> points, int Point::* coord)
{
    vector<double> result;
    for (auto& p: points)
        result.push_back(p.*coord);
    return result;
}
// usage:
vector<double> Xs = Project(points, &Point::x);
vector<double> Ys = Project(points, &Point::y);

还有许多其他用法,例如快速委托(链接)。

这些是指向类成员的指针,例如用于实现各种函子类(例如:boost::functionstd::function)。

http://en.cppreference.com/w/cpp/utility/functional/mem_fn

http://www.cplusplus.com/reference/std/functional/mem_fun/

class Point {
   public: //public variables (can be accessed by outsider)
   float x, y;
   private: //private variables if you have any
};

现在要创建一个对象,可以执行Point p,并且可以通过执行p.xp.y来访问元素,就像使用struct对象一样。

如果要创建类指针,请执行Point *p,现在如果要访问x, y,则执行p->ap->b。如果您有另一个对象Point t,并且您想将t的地址分配给p,那么您可以执行p = &t