如何将sizeof()运算符应用于非静态类成员方法? [英] How to apply sizeof() operator to non-static class member methods?

查看:133
本文介绍了如何将sizeof()运算符应用于非静态类成员方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct MyClass {
  int foo () { return 0; }
};

unsigned int size = sizeof(MyClass::foo);  // obviously error

我们可以应用 sizeof()外部 的成员方法?我们需要声明对象才能得到它吗?

Can we apply sizeof() to member methods from outside the class ? Do we need to declare object to get it ?

编辑:我知道上面的代码会给出错误(这就是为什么明显 。想知道我们是否可以将sizeof()应用于成员方法。

Edit: I know that above code will give error (that's why word 'obviously'). Wanted to know if we can at all apply the sizeof() to a member method. I don't want to describe the use case for that in length.

推荐答案

您无法获得的大小。成员函数,但您可以获取指针到成员函数的大小:

You cannot obtain the size of a member-function, but you can obtain the sizeof a pointer-to-member-function:

int size = sizeof( &MyClass::foo );

非成员函数(和静态成员函数)也是如此,函数的大小不能获得。这可能是误导,因为在大多数上下文中,函数的名称​​自动衰减到指向函数的指针基本上与数组衰减到指向第一个元素,但是在数组的情况下, sizeof 不会触发衰减,这反过来意味着你必须请求指针明确。

The same goes for non-member functions (and static member functions), the size of the function cannot be obtained. It might be misleading because in most contexts, the name of the function decays automatically into a pointer to the function basically in the same way that an array decays to a pointer to the first element, but as in the case of arrays, sizeof does not trigger the decay and that in turn means that you have to ask for the pointer explicitly.

这篇关于如何将sizeof()运算符应用于非静态类成员方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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