用C ++代码初始化C结构 [英] Initialising C structures in C++ code

查看:162
本文介绍了用C ++代码初始化C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法来初始化C ++代码中的C结构?

Is there a better way to initialise C structures in C++ code?

我可以在变量声明点使用初始化程序列表;但是,如果在编译时不知道所有参数,或者如果我没有声明本地/全局实例,则此功能就没有用了,例如:

I can use initialiser lists at the variable declaration point; however, this isn't that useful if all arguments are not known at compile time, or if I'm not declaring a local/global instance, eg:

声明结构的传统C代码,并且具有使用API​​的

Legacy C code which declares the struct, and also has API's using it

typedef struct
{
    int x, y, z;
} MyStruct;

使用C库的C ++代码

C++ code using the C library

void doSomething(std::vector<MyStruct> &items)
{
    items.push_back(MyStruct(5,rand()%100,items.size()));//doesn't work because there is no such constructor
    items.push_back({5,rand()%100,items.size()});//not allowed either

    //works, but much more to write...
    MyStruct v;
    v.x = 5;
    v.y = rand()%100;
    v.z = items.size();
    items.push_back(v);
}

创建本地实例,然后一次将每个成员设置为一个(myStruct.x = 5;等)确实很痛苦,并且在尝试向容器中添加说20种不同项时有些难以阅读...

Creating local instances and then setting each member one at a time (myStruct.x = 5; etc) is a real pain, and somewhat hard to read when trying to add say 20 different items to the container...

推荐答案

如果您无法添加构造函数(这是C ++ 03中的最佳解决方案,但您可能与C具有兼容性限制),则可以编写一个功能具有相同的效果:

If you can't add a constructor (which is the best solution in C++03 but you probably have compatibility constraint with C), you can write a function with the same effect:

MyStruct makeAMyStruct(int x, int y, int z)
{
    MyStruct result = { x, y, z };
    return result;
}

items.push_back(makeAMyStruct(5,rand()%100,items.size()));

我现在已经检查过C ++ 0X为这个精确的问题提供了一些东西:

I'd have checked now that C++0X offers something for this precise problem:

items.push_back(MyStruct{5,rand()%100,items.size()});

在g ++ 4.4中可用.

which is available in g++ 4.4.

这篇关于用C ++代码初始化C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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