第1个回答 推荐于2016-06-04
C++中的STRUCT可以有成员函数(方法),但是C不能有,例如下面的结构体:
#include <stdio.h>
struct SAMPLE
{
int a,b,c;
void Set(int x,int y,int z){a=x;b=y;c=z;}
char*toStr(){char p[20]={0};sprintf(p,"%d %d %d",a,b,c);return p;}
};
调用:
struct SAMPLE q;
q.Set(100,132,152);
printf("%s\n",q.toStr());
结果为:100 132 152
在C++中可以编译通过并运行正常,但是在C中不能!
C中,应该换成:
#include <stdio.h>
struct SAMPLE
{
int a,b,c;
};
void Set(struct SAMPLE & TODO,int x,int y,int z)
{
TODO.a=x;
TODO.b=y;
TODO.c=z;
}
char*toStr(struct SAMPLE todo)
{
char p[20]={0};
sprintf(p,"%d %d %d",todo.a,todo.b,todo.c);
return p;
}
调用方法:
struct SAMPLE q;
Set(q,13,12,0);
printf("%s\n",toStr(q));
结果为:13 12 0
明白了吧~本回答被提问者采纳