C++ 将 "struct"类型的参数作为引用(和)传递或按值传递

标签 c++ struct

我在 C++ 中有以下函数:

Family whoAmI(Family myFam,string MyName, int MyAge)
{
    myFam.Name = MyName;
    myFam.Age = MyAge;
    return myFam;
}

它返回一个这种类型的struct:

struct Family
{
    string Name;
    int Age;
};

我的问题是:我希望我的函数返回一种特定类型的 struct,在我们的示例中是 Family,但是为了指定函数,我必须先声明结构,并将其转换为函数的返回类型,如下所示:Family whoAmI() {..}。然后我必须将函数中的值添加到 struct 中,它最终类似于 Family。这意味着我需要在函数本身中重新声明一个类似的 struct(这非常耗费内存)。我所做的是将 struct 的引用传递给函数,以防止函数中 struct 的重复。现在,这是正确的吗?由于它在参数中占有一席之地,因此不太方便。

现在,我这样调用它:

Family x;
Family result = whoAmI(x, "Mostafa", 25);

最佳答案

使用构造函数。

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

关于C++ 将 "struct"类型的参数作为引用(和)传递或按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27058890/

相关文章:

c++ - 使用前重置成员变量

c++ - `const &&` 是否绑定(bind)到所有 prvalues(和 xvalues)?

c++ - 打包结构成员的传递地址

c - 在结构函数中分配动态数组

c - 如果内存大小相等,如何将 C 结构转换为另一种结构类型?

python - 如何使用 python 结构将结构打包到结构中?

c++ - 将奇异对齐的对象置于协程状态是否是定义的行为?

c++ - OpenGL 相机俯仰、偏航和滚动旋转

c - 线程结构作为函数参数 C

c - 程序不想读取文件