是否有一些使用Object::*的实际示例
Are there some practical examples that use Object::*
我刚刚听说有一种类型像这样,一个指向对象的成员。这是
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::function
或std::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.x
和p.y
来访问元素,就像使用struct
对象一样。
如果要创建类指针,请执行Point *p
,现在如果要访问x, y
,则执行p->a
和p->b
。如果您有另一个对象Point t
,并且您想将t
的地址分配给p
,那么您可以执行p = &t
。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 返回 *&object 时是否允许复制/移动省略?
- 在非构造"object"上调用非虚拟成员函数是否定义良好?
- 名称查找是否应该"in the class of the object expression"查找该类的成员?
- 是否有一些使用Object::*的实际示例
- C++是否有一个自由函数“size(object)”