什么是C ++相当于C中的指定初始化? [英] What is the C++ equivalent to C's designated initializers?

查看:144
本文介绍了什么是C ++相当于C中的指定初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在C声明结构像这样:

You can declare a structure in C like so:

typedef struct MyStruct {
    const char *name;
    int (*func1)(void);
    int (*func2)(void);
    int (*func3)(void);
} MyStruct;

int test_func2(void) {
    return 0;
}

MyStruct test_struct = {
    .name   = "buffer",
    .func2  = test_func2,
};

这是很方便的定义只有特定的成员,所有其他的人被设置为0 / NULL。

This is quite handy for only defining particular members, all the other ones being set to 0/NULL.

编辑:特别是,这允许不知道的MYSTRUCT是如何定义的细节,所以可以在内部发生变化,增加新的部件等。不使用这种类型的流汗code

in particular, this allows to not know the details of how MyStruct is defined, so it can change internally, adding new members etc.. without ever breaking code using this type.

这不会与C ++编译器编译但是,收到错误:

This wouldn't compile with a C++ compiler however, getting error:

test.c:23: error: expected primary-expression before ‘.’ token
test.c:24: error: expected primary-expression before ‘.’ token

时有一个相当于C ++声明殊途同归?

Is there an equivalent C++ declaration achieving the same?

感谢。

编辑:@克里斯我可以告诉你不明白:)
这是相当明显,其他大多数人在评论我应该用什么语法,如何结构应被定义等已经完全忽略了一点。这不是正确的方式来定义一个结构,这个片段在那里只提供一个环境。

@chris I can tell you don't understand :) And It's quite obvious that most other people commenting on what syntax I should have used, how the structure should have been defined etc.. have completely missed the point. This isn't about the correct way to define a structure, this snippet was only there to provide a context.

至于code等价,
地方说,在你的code你所做的:

As for code equivalence, Say somewhere in your code you did:

MyStruct blah = { NULL, NULL, func2 };

现在MYSTRUCT改变它的定义是:

Now MyStruct change its definition to be:

typedef struct MyStruct {
  const char *name;
  int (*func4)(void);
  int (*func1)(void);
  int (*func2)(void);
  int (*func3)(void);
} MyStruct;

您code仍将编得很好,但已经推出了严重的回归:而不是设置FUNC2像以前那样,你现在会初始化func1的成员...

Your code will still compile just fine, but has introduced a serious regression : instead of setting func2 like it used to, you would now initialise func1 member...

问题是关于有没有C ++指定的初始值等价的:没有。问题关闭。

The question was about is there C++ designated initializers equivalent: there isn't. problem closed.

推荐答案

没有,C ++不支持C99的指定初始化。如果你想通过名字来设置各个成员,则需要通过分配,例如做。

No, C++ does not support C99's designated initializers. If you want to set individual members by name, you'll need to do it via assignment, e.g.

MyStruct test_struct = MyStruct();
test_struct.name  = "buffer";
test_struct.func1 = test_func1;

这篇关于什么是C ++相当于C中的指定初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆