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

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

问题描述

我遇到了这个奇怪的代码片段,它编译得很好:

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

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

为什么一个类的静态数据成员? 是什么在实际代码中使用这个奇怪的指针?

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.

编辑:对于指向成员数据的指针的令人信服的使用。指向成员函数的指针可以用于可插拔的架构,但是再次在小空间中产生一个例子会打败我。以下是我最好的(未测试的)try - 一个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.

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

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