今天在翻unix网络编程的时候,无意中看到了使用匿名定义结构体/类定义数组的一段代码。
于是写了测试代码如下:
#include
#include
#include
#include
using namespace std;
struct st
{
int a;
int b;
char *p;
int c;
}sts[]={
{1,1,"hh",1},
{2,2,"ff",2}
};
class CObj
{
public:
int a;
string s;
int b;
}objs[]={
{1,"x",11},
{2,"y",22}
};
int main(int argc, const char *argv[])
{
for (int i = 0; i < 2; i++) {
printf("%d,%d,%s,%d\n",(sts+i)->a,(sts+i)->b,(sts+i)->p,(sts+i)->c);
}
for (int i = 0; i < 2; i++) {
printf("%d,%s,%d\n",(objs+i)->a,(objs+i)->s.c_str(),(objs+i)->b);
}
}
运行结果如下:
1,1,hh,1
2,2,ff,2
1,x,11
2,y,22
整个调用过程中,都没有用st或者CObj显示创建任何参数,调用起来要简洁很多,简直比python还要简洁。
用python的代码来表示的话:
sts = (
(1,1,"hh",1),
(2,2,"ff",2)
)
但python不支持匿名类的定义,只能用下标来访问数据,这样看来倒是C的表现更好一些呢。
记录一下,有机会在项目中用一下。