简体   繁体   中英

C++ passing argument of “struct” type as reference (&) or passing it by value

I have the following function in 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 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() {..} . Then I have to add values in the function to a struct which ends up being similar to Family . This means that I need to re-declare a similar struct in the function itself (which is quite memory consuming). What I did was to pass a reference of struct to the function to prevent a duplication of struct in the function. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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