简体   繁体   English

函数指针作为结构的静态成员

[英]function pointer as static member of a structure

Please look at the definition of the structure below: 请查看以下结构的定义:

struct rectangle
{
   int len,bre;
   static int diagonal;
   static (int) (*ptr) (int,int);
};

int rectangle::diagonal;
rectangle::ptr; // (WHAT SHOULD COME HERE)

rectangle r1,r2;

Hi friends, I have defined a structure here. 嗨,朋友们,我在这里定义了一个结构。 We know that the size of 'r1' or 'r2' is sum of the members 'len and 'bre' only. 我们知道'r1'或'r2'的大小仅是成员'len和'bre'的总和。

Now to allocate memory for the static members we must do it explicitly. 现在要为静态成员分配内存,我们必须显式地进行分配。 The allocation for the static member diagonal is fine. 静态成员对角线的分配很好。 But what should I give in the place: (WHAT SHOULD COME HERE) so that the memory allocation for the function pointer is fine. 但是我应该在该位置给出什么:(应该在此处显示),以便为函数指针分配内存。

Hope my explanation is clear to you. 希望我的解释对您清楚。 Please do help me. 请帮帮我。

The easiest way is to typedef a function and use it there: 最简单的方法是对一个函数进行typedef定义并在其中使用它:

typedef int (*MyFunction) (int,int);
struct rectangle
{
    ...
    static MyFunction ptr;
};
MyFunction rectangle::ptr = /*initialize it here*/

But also you can do it as int (*rectangle::ptr)(int,int) 但是你也可以将它作为int(* rectangle :: ptr)(int,int)

Below is the correct way: 下面是正确的方法:

struct rectangle
{
...
   static int (*ptr) (int,int);
       // ^^^ no braces needed
};

int (rectangle::*ptr) (int, int);
//   ^^^^^^^^^^^^^^ defining a function pointer

Whenever there is a confusion related to function pointer, make a typedef and use it: 每当与函数指针相关的混乱时,请创建typedef并使用它:

typedef int (*fptr) (int,int);
struct rectangle
{
   static fptr ptr;
};

fptr rectangle::ptr;

Try: 尝试:

struct rectangle
{
   int len,bre;
   static int diagonal;
   static int (*ptr) (int,int);
};

int rectangle::diagonal;
int (*rectangle::ptr)(int,int) = NULL;

rectangle r1,r2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM