使用指针到C中的结构内部的函数

ble*_*ter 1 c struct data-structures

只是为了s&g.我想在C中构建自己的库.我想让它遵循C#对象的概念,并意识到这样做的唯一方法是让基类型使用函数指针作为它们的成员.

好吧,我被卡住了,不知道为什么.以下是String基类型的示例:

#ifndef STRING_H
#define STRING_H

typedef struct _string
{
    char* Value;
    int Length;
    String* (*Trim)(String*, char);

} String;

String* String_Allocate(char* s);
String* Trim(String* s, char trimCharacter);

#endif  /* STRING_H */
Run Code Online (Sandbox Code Playgroud)

并实施:

String* Trim(String* s, char trimCharacter)
{
    int i=0;
    for(i=0; i<s->Length; i++)
    {
        if( s->Value[i] == trimCharacter )
        {
            char* newValue = (char *)malloc(sizeof(char) * (s->Length - 1));
            int j=1;

            for(j=1; j<s->Length; j++)
            {
                newValue[j] = s->Value[j];
            }

            s->Value = newValue;
        }
        else
        {
            break;
        }
    }

    s->Length = strlen(s->Value);
    return s;
}

String* String_Allocate(char* s)
{
    String* newString = (String *)malloc(sizeof(String));
    newString->Value = malloc(strlen(s) + 1);
    newString->Length = strlen(s) + 1;
    strcpy(newString->Value, s);

    newString->Trim = Trim;
}
Run Code Online (Sandbox Code Playgroud)

但是,在NetBeans中编译时(对于c,C++),我收到以下错误:

In file included from String.c:6:
String.h:8: error: expected specifier-qualifier-list before ‘String’
String.c: In function ‘String_Allocate’:
String.c:43: error: ‘String’ has no member named ‘Trim’
make[2]: *** [build/Debug/GNU-Linux-x86/String.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 77ms)
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我理解String-> Trim成员如何不存在和/或如何解决这个问题?

谢谢

Nor*_*sey 5

使用递归结构,您需要编写

typedef struct _string String;
Run Code Online (Sandbox Code Playgroud)

定义结构之前,或者在内部String替换它的地方struct _string(直到typedef进入范围).