问题
I am trying to pass a coordinate, which is defined as struct with 2 integer parameters (the struct is called coord) the following way:
UpdateB({0,0});
where the input argument is of type coord (i.e. in the above statement I am trying to pass a coordinate 0,0
). UpdateB
is some function. I am getting an error, any ideas what
the problem could be?
回答1:
Make a constructor accepting two argumnets. Pass it as follows:
MyFunc(Point2d(0,0));
回答2:
Pavel's got it spot on. If you want to create the struct instance as you're passing it to the function, you'll need to make a constructor for it. Then create a new instance of coord as the argument you're passing to the function. For the struct, something like...
struct coord
{
int x, y;
coord(int xvalue, int yvalue)
{
x = xvalue;
y = yvalue;
}
};
...should do the trick. Then just run...
UpdateB(coord(x, y));
...where x and y are your values.
回答3:
The syntax you are using would be valid C++0x (uniform initializers) and valid C99 (compound literals).
In C++03 you have to use either user-defined constructors or helper functions, the curly-brace syntax only works for aggregate initialization.
If your struct is a POD and you need it to stay one, you have to use a helper function:
coord make_coord(int x, int y) {
coord c = {x, y};
return c;
}
UpdateB(make_coord(x, y));
Otherwise, as already mentioned, give it a constructor
回答4:
Pavel Radzivilovsky's solution is right (+1).
However you have to know that the coming new standart C++0x will allow the syntax of your example if you provide a constructor with two parameters (and maybe if you provide a constructor with initializer list but that's not useful here).
This feature is already available in GCC starting v4.4, if you use it you can enable it by enabling C++0x.
来源:https://stackoverflow.com/questions/3126781/passing-a-struct-with-multiple-entries-in-c