简体   繁体   English

直接将结构传递给功能

[英]passing structure directly to function

I have a struct that I initialize like this: 我有一个像这样初始化的结构:

typedef struct
{
 word w;
 long v;
}
MyStruct;


MyStruct sx = {0,0};
Update(sx);

Now, it seems such a waste to first declare it and then to pass it. 现在,先声明它然后再传递它似乎很浪费。 I know that in C#, there's a way to do everything in one line. 我知道,在C#中,有一种方法可以将所有内容统一处理。 Is there any possiblity of passing it in a more clever (read: cleaner) way to my update function? 是否有可能以更聪明的方式(更干净)将其传递给我的更新功能?

In C++, structs are the same as classes except in structs everything is public by default. 在C ++中,结构与类相同,但在结构中,默认情况下所有内容都是公共的。 So you can give a struct a constructor, eg 所以你可以给一个结构构造函数,例如

struct MyStruct
{
 word w;
 long v;

 MyStruct(word w, long v) : w(w), v(v) {}
};


Update(MyStruct(0,0));

Also, C-style struct typedef'ing is unnecessary and discouraged in C++. 同样,C风格的结构类型定义是不必要的,并且在C ++中不建议使用。

It depends on how your Update is declared. 这取决于如何声明Update If it expects a value of MyStruct type or a reference of const MyStruct& type, you can just do 如果期望使用MyStruct类型的值或const MyStruct&类型的引用,则可以执行以下操作

Update(MyStruct());

This is possible because you wanted to initialize your object with zeroes (which is what the () initializer will do in this case). 这是可能的,因为您想用零初始化对象(这是()初始化程序在这种情况下的作用)。 If you needed different (non-zero) initializer values, you have to either provide a constructor for MyStruct or do it the way you do it in your question (at least in the current version of the C++ language). 如果需要不同的(非零)初始化器值,则必须为MyStruct提供构造函数,或者以在问题中使用它的方式进行构造(至少在当前版本的C ++语言中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM