C ++:指向复合类数据成员的指针

编程入门 行业动态 更新时间:2024-10-24 10:19:32
本文介绍了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 ++:指向复合类数据成员的指针

本文发布于:2023-07-28 02:41:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   成员   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!