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

时间:2011-04-12 01:25:56

标签: c data-structures struct

仅限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 */

实施:

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;
}

但是,在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)

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

谢谢

3 个答案:

答案 0 :(得分:5)

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

typedef struct _string String;
在之前

定义结构,或者在String内部用struct _string替换它(直到typedef进入范围)。< / p>

答案 1 :(得分:0)

将其分解为单独的typedef和字段声明,看看是否有帮助。

答案 2 :(得分:0)

该对象不存在,因为在.h文件中定义它的代码有语法错误,因此该错误产生了其他错误。这些天编译和运行是如此便宜,你可能只修复第一个错误,并重新编译。随着您获得经验,您将认识到哪些错误是早期错误的结果。

你可能想在C语言中做一个关于面向对象编程的研究机器人,因为有些人在C ++存在之前就已经这样做了。 http://www.planetpdf.com/codecuts/pdfs/ooc.pdf