这里给出的代码在用g++编译时运行良好,但在用gcc编译时出现错误。显然,这对于C++是正确的,但对于C却不是。请帮助我纠正C的语法。
# include <stdio.h>
typedef struct demo
{
int arr[20], i;
void setvalue(int num)
{for(i=0;i<20;i++)arr[i]=num;}
void printvalue()
{for(i=0;i<20;i++)printf("%d ",arr[i]);}
} example;
int main()
{
example e;
e.setvalue(100);
e.printvalue();
return 0;
}错误日志:
stov.c:7:2: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘{’ token
stov.c: In function ‘main’:
stov.c:18:3: error: ‘example’ has no member named ‘setvalue’
stov.c:19:3: error: ‘example’ has no member named ‘printvalue’发布于 2011-07-17 03:29:20
在C中不能有方法(结构中的函数)。有不止一种方法可以解决这个问题,但我只需将对象作为第一个参数传递给函数:
void setvalue(struct demo *d, int num)
{
int i;
for(i = 0; i < 20; i++)
d->arr[i] = num;
}
/* ... */
setvalue(&e, 100);发布于 2011-07-17 03:30:27
这就是你的问题:你的struct包含方法。这在C中是不好的。
在C++中,struct很像class (或者更确切地说,class很像struct),并且可以有方法,等等。
在C中,这不适用。
发布于 2011-07-17 08:33:28
你可以在struct中使用函数指针来模拟OOP。
typedef struct demo
{
int arr[20], i;
void (*setvalue)(int num);
void (*printvalue)();
} example;然后,您可以稍后将函数赋值给函数指针。
void set_val(int num) {for(i=0;i<20;i++)arr[i]=num;}
example_struct.setvalue = set_val;https://stackoverflow.com/questions/6719701
复制相似问题