指向类数据成员":: *"的指针

编程入门 行业动态 更新时间:2024-10-19 01:25:22
本文介绍了指向类数据成员":: *"的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

指向类数据成员":: *"的指针

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

发布评论

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

>www.elefans.com

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