【发布时间】: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