[英]Pass struct member to function pointer in same struct in C
I need to pass a struct member such as "str" in the following example as an argument to a function pointer in same struct such as "(ToUpper)", or by another words I need to access the value of "str" inside the "ToUpper" function. 在下面的示例中,我需要传递一个结构成员(例如“ str”)作为同一结构(例如“(ToUpper)”)中函数指针的参数,或者换句话说,我需要在内部访问“ str”的值“ ToUpper”功能。
typedef struct _String {
char* str;
char* (*ToUpper) (void);
} String;
Can I do it in this way ? 我可以这样吗?
Since there's no this
pointer in C, you have to pass a reference to whatever object you're manipulating when working with function pointers in structs... 由于C语言中没有this
指针,因此在结构体中使用函数指针时,您必须传递对要处理的任何对象的引用...
typedef struct _String {
char* str;
char* (*ToUpper)( struct _String );
} String;
Then you should have an "initialize" function that is like this.. 然后,您应该有一个像这样的“初始化”功能。
char* ToUpper( struct _String s ) {
// ...
}
String newString(char* str) {
return (String) { str, ToUpper };
}
That second method there will give you a new String struct with all the function pointers set so you can use it. 那里的第二种方法将为您提供一个新的String结构,并设置所有函数指针,以便您可以使用它。
Call it like this: 这样称呼它:
someString.ToUpper(someString)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.