[英]C++ passing argument of “struct” type as reference (&) or passing it by value
I have the following function in C++: 我在C ++中具有以下功能:
Family whoAmI(Family myFam,string MyName, int MyAge)
{
myFam.Name = MyName;
myFam.Age = MyAge;
return myFam;
}
It returns a struct
of this type: 它返回这种类型的struct
:
struct Family
{
string Name;
int Age;
};
My question is that: I want my function to return a specific kind of struct
which in our example is Family
, but in order to specify the return type of the function, I have to declare the struct first, and cast it as the return type of function, like this: Family whoAmI() {..}
. 我的问题是:我希望函数返回特定类型的struct
,在我们的示例中为Family
,但是为了指定函数的返回类型,我必须先声明该结构并将其转换为返回类型功能,例如: Family whoAmI() {..}
。 Then I have to add values in the function to a struct
which ends up being similar to Family
. 然后,我必须在函数中添加值的struct
,其最终被类似Family
。 This means that I need to re-declare a similar struct
in the function itself (which is quite memory consuming). 这意味着我需要在函数本身中重新声明一个类似的struct
(这非常消耗内存)。 What I did was to pass a reference of struct
to the function to prevent a duplication of struct
in the function. 我所做的是将struct
的引用传递给函数,以防止在函数中重复struct
。 Now, is this correct? 现在,这是正确的吗? Since it occupies a place in arguments and thus making it less convenient. 由于它在争论中占有一席之地,因此较不方便。
Now, I call it like this: 现在,我这样称呼它:
Family x;
Family result = whoAmI(x, "Mostafa", 25);
Use a constructor. 使用构造函数。
struct Family {
Family(const std::string& Name, int Age)
: Name(Name), Age(Age) {}
std::string Name;
int Age;
};
// use like:
Family me{"AName", 45}; // or Family me("AName", 45); on old compilers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.