【问题标题】:Using Pointer to Functions Inside Structs in C在 C 中使用指向结构内部函数的指针
【发布时间】:2011-04-12 01:25:55
【问题描述】:

只为 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->Trim 成员不存在和/或如何解决这个问题?

谢谢

【问题讨论】:

  • 如果您希望能够进行任何多态性,请查看 GObject。或者只使用 C++ - C 不是面向对象的,在我看来,你尝试这样做的那一刻就是你不应该使用它的时候。最常见的症状之一似乎是对struct 进行类型定义...

标签: c data-structures struct


【解决方案1】:

使用递归结构你需要编写

typedef struct _string String;

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

【讨论】:

  • 你能写出声明吗?我不知道那是什么意思。
  • String* (*Trim)(String*, char); 更改为struct _string* (*Trim)(struct _string*, char);
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    该对象不存在,因为在 .h 文件中定义它的代码存在语法错误,因此该错误引发了其他错误。现在编译和运行非常便宜,你不妨只修复第一个错误,然后重新编译。随着经验的积累,您将认识到哪些错误是由早期错误造成的。

    您可能想对 C 中的面向对象编程进行一些研究,因为在 C++ 出现之前就已经有人这样做了。 http://www.planetpdf.com/codecuts/pdfs/ooc.pdf

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多