Initialising C structures in C++ code

冷暖自知 提交于 2019-12-10 15:23:30

问题


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:

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

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

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);
}

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...


回答1:


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()));

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

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

which is available in g++ 4.4.




回答2:


You're looking for C99 compound literals. Example code:

struct foo *foo = malloc(sizeof *foo);
*foo = (struct foo){ bar, baz };



回答3:


How about:

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



回答4:


Not clear what you are asking. In C++, the obvious solution is to give the struct a constructor:

struct MyStruct {
  int x, y, z;
  MyStruct( int ax, int ay, int az ) : x( ax ), y( ay ), z( az ) {}
};



回答5:


Create a function to initialize it, similar to what a C++ constructor would do.




回答6:


Another option is to derive from the struct and add a constructor there.

struct MyDerivedStruct : public MyStruct
{
    MyDerivedStruct(int xi, int yi, int zi)
    {
        x = xi;
        y = yi;
        z = zi;
    }
}

Then you can use this derived type in your own code and pass it to the C library when necessary. The language should take care of implicitly converting to MyStruct when appropriate.

As a bonus, you could also add other useful member functions, perhaps even wrapping many of the legacy C functions that use this type.



来源:https://stackoverflow.com/questions/1994841/initialising-c-structures-in-c-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!