开发者

Initialising C structures in C++ code

开发者 https://www.devze.com 2022-12-15 03:23 出处:网络
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

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 stru开发者_Python百科ct
{
    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...


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.


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

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


How about:

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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消