什么是指向成员的指针和指向函数的指针 [英] what is advantage pointer-to-member and pointer-to-function

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

问题描述

大家好,



最后一次采访,我得到一个问题,指针成员,普通成员函数和指向函数的指针对数据成员的优势指标是什么。

解决方案

一般注意事项:在C ++中,您应该避免使用原始指针(任何类型)作为原则,除了编写专门设计的框架的目的帮助系统的其他部分避免指针。你应该使用的是智能指针。



鉴于此,我认为这个问题是对你的理解的低级评估,因此,解释将是如下:



指向数据成员的指针:

这打破了封装,永远不应该使用。但是,您可以使用指向 const 数据成员的指针作为以有效方式将数据引用传递给另一个函数的方法。



数据成员指针:


由于类似的原因,您可以将指针用作数据成员而不是数据本身你会在当地的职能部门,例如g。:

- 如果你需要偶尔将数据传递给其他函数,并且复制数据类型很昂贵,最好使用指针

- 如果数据可能有 NULL 值,但数据类型没有定义一个,使用 nullptr 作为 NULL value是一个选项

- 如果拥有数据的类可以(并且预期)被复制(很多),但数据元素通常不是修改后,类的实例通过使用指针共享数据元素可能更明智(但是,使用智能指针会更好!)



成员函数指针:


除非你是一个非常先进的系统/框架程序员,否则别忘了。类和(虚拟)成员函数使得任何类型的函数指针都过时了,除了编译器编程(在这种情况下,将负责使函数指针的使用过时)

他们是不同的野兽,服务于不同的目的。所以我没有看到使用其中一个的任何优势。

您确定准确报告了面试问题吗?


Hi everyone,

Last interview, i got a question what is the advantage pointer to data member over the pointer member, normal member function and pointer to function.

解决方案

A general note: in C++ you should avoid using raw pointers (of any kind) as a matter of principle, except for the purpose of writing frameworks specifically designed to help other parts of the system avoiding pointers. What you should use are smart pointers.

Given that, I assume the question is intended as a low level evaluation of your understanding, and thus, the explanations would be as follows:

Pointer to data member:
This breaks encapsulation and should never be used. However, you can use a pointer to const data member as a means to pass a data reference to another function in an efficient way.

Data member pointer:

You can use a pointer as a data member rather than the data itself for similar reasons as you would in a local function, e. g.:
- If you need to pass the data to other functions occasionally, and the data type is expensive to copy, using a pointer is preferable
- If the data could have a NULL value, but the data type doesn't define one, using nullptr as NULL value is an option
- if the class that owns the data can (and is expected to) be copied (a lot), but the data element is not usually modified, it may be more sensible for the instances of the class to share the data element by using a pointer (however, it would be even better to use a smart pointer!)

Member function pointer:

Just forget about that unless you are a highly advanced system/framework programmer. Classes and (virtual) member functions make function pointers of any kind pretty much obsolete, except in compiler programming (in which case you would be the one responsible for making the use of function pointers obsolete)


They are different beasts and serve different purposes. So I don't see any 'advantage' in using one or the other.
Are you sure you reported the interview question exactly?


这篇关于什么是指向成员的指针和指向函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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