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

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

问题描述

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

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++ 有指向类的非静态数据成员的 this 指针?这个奇怪的指针在实际代码中有什么用?

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天全站免登陆