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

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

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

发布评论

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

>www.elefans.com

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