简体   繁体   中英

Function that returns parameters C++

Hello I have a little problem and I would be happy if you could tell me how to fix it. So I have a function which is the realization like this :

int* getMytree()

The function should return three variables. The variables are defined as public.

How do I return the three parameters ?

Apart from wrapping three variables inside a struct

You can return a std::tuple

std::tuple<int, int, int> getMytree(int id)
{
   // ....
   // a= , b= c=
   return std::make_tuple( a,b,c );
}

And then use std::tie with your public variables as :

 std::tie( var1, var2, var3 ) = getMytree() ;

Sorry there's no way to explicitly return three values from a function as function can return only one value. However you could do two things

1) Encapsulate those three parameters in a struct and then make function to return that struct.

struct Book
{
int pages;
std::string name;
std::string author
};

Book myFunc ();  // This example is just for simplicity.

2) More simply pass pointers/references to three parameters you want the function to change.

void myFunc ( int& page, std::string &name, std::string &author );

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