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

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

问题描述

是否可以访问具有指向成员的指针的复合类数据成员?以下代码无效,但表明需要。

Is it possible to access a composite class data member with pointers to members ? The following code is not valid but demonstrate the need.

例如:

class A
{
public:
    float fA;
};

class B
{
public:
    float fB;
    A a;
};

void test()
{
    // Use of member pointer to access B::fB member
    float B::*ptr = &B::fB; // -> OK
    B myB;
    myB.*ptr = 25.;

    // Use of member pointer to access B::a.fA member ???
    float B::*ptr2 = &B::a.fA; // -> ERROR
    B myB.*ptr2 = 25.;
}

我在这里完成我的问题:指向复合类数据成员的指针 - 第2部分

I've complete my question here : Pointer to composite class data member - Part 2

推荐答案

没有你不能,因为C ++语法不允许。我没有看到任何真正特别的你想要做什么,但它根本不考虑在语言。

No you cannot because the C++ syntax does not allow it. I don't see anything really special about what you're trying to do, but it's simply not considered in the language.

注意,一个指向数据成员的指针是一个给定实例的对象将返回对特定数据成员的引用。您可以手动实现此功能,放宽限制:

Note however that a pointer to data member is an object that given an instance will return a reference to a specific data member. You can implement this functionality manually relaxing the limitations:

struct A
{
    double x;
    double y;
    static double& x_of(void *p) { return ((A *)p)->x; }
    static double& y_of(void *p) { return ((A *)p)->y; }
};

struct B
{
    double z;
    A a;
    static double& x_of(void *p) { return ((B *)p)->a.x; }
    static double& y_of(void *p) { return ((B *)p)->a.y; }
    static double& z_of(void *p) { return ((B *)p)->z; }
};

指针的类型只是 double& (*)(void *),你可以使用这种技巧,例如返回作为数组元素的成员。

The type of the pointer is just double& (*)(void *) and you can use this kind of trick even for example to return as member an element of an array.

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

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