指向类数据成员":: *"的指针 [英] Pointer to class data member "::*"

查看:264
本文介绍了指向类数据成员":: *"的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到了这个奇怪的代码片段,可以很好地编译:

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
    return 0;
}

为什么为什么C ++具有指向类的非静态数据成员的指针? 在实际代码中的用途是什么?

Why does C++ have this pointer to a non-static data member of a class? What is the use of this strange pointer in real code?

推荐答案

它是指向成员的指针"-以下代码说明了其用法:

It's a "pointer to member" - the following code illustrates its use:

#include <iostream>
using namespace std;

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;

    Car c1;
    c1.speed = 1;       // direct access
    cout << "speed is " << c1.speed << endl;
    c1.*pSpeed = 2;     // access via pointer to member
    cout << "speed is " << c1.speed << endl;
    return 0;
}

关于为什么,您想这样做,那么它为您提供了另一种可以解决一些棘手问题的间接访问级别.但是说实话,我从来没有在自己的代码中使用它们.

As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.

编辑:我不能认为有说服力的使用指向成员数据的指针.指向成员函数的指针可用于可插拔体系结构,但再次在较小的空间中产生示例使我失望.以下是我最好的(未尝试的)尝试-一个Apply函数,该函数将在用户选择的成员函数应用于对象之前进行一些前置和后置处理:

I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:

void Apply( SomeClass * c, void (SomeClass::*func)() ) {
    // do hefty pre-call processing
    (c->*func)();  // call user specified function
    // do hefty post-call processing
}

由于->*运算符的优先级低于函数调用运算符的优先级,因此必须在c->*func周围加上括号.

The parentheses around c->*func are necessary because the ->* operator has lower precedence than the function call operator.

这篇关于指向类数据成员":: *"的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆