今天在翻unix网络编程的时候,无意中看到了使用匿名定义结构体/类定义数组的一段代码。

于是写了测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <vector>
#include <map>
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的代码来表示的话:

1
2
3
4
sts = (
    (1,1,"hh",1),
    (2,2,"ff",2)
)

但python不支持匿名类的定义,只能用下标来访问数据,这样看来倒是C的表现更好一些呢。

记录一下,有机会在项目中用一下。





原创文章,版权所有。转载请注明:转载自Vimer的程序世界 [ http://www.vimer.cn ]

本文链接地址: http://www.vimer.cn/?p=1647

5 个评论 在 “c、cpp中使用匿名结构体、类定义数组”

  1. 瑞士菜刀 说:

    话说「匿名」结构体/类是指不写明本身名称的结构体/类吧… 写了 struct st / class CObj 就不叫匿名了.

    struct { … } sts[] = { … };
    class { … } objs[] = { … };

    [回复]

    Dante 回复:

    确实如此,我在文中的说法不是很准确,呵呵。
    之前居然被自动过滤到垃圾评论里面去了。。

    [回复]

    Dante 回复:

    我刚才又试了一下:
    struct
    {
    int a;
    int b;
    char *p;
    int c;
    }sts[]={
    {1,1,”hh”,1},
    {2,2,”ff”,2}
    };

    class
    {
    public:
    int a;
    string s;
    int b;

    }objs[]={
    {1,”x”,11},
    {2,”y”,22}
    };

    把名字去掉,这样写也是没问题的。。。。

    [回复]

  2. 依云 说:

    原来class也可以这么用啊,学习了。
    不过Python有namedtuple呀。另外, “都没有用st或者CObj显示创建任何参数”这里有错别字哦~

    [回复]

    Dante 回复:

    咦,我去研究下.哈,你看得好仔细呀,我改一下.

    [回复]

我要评论

*

*