Sign in to follow this  
chrisliando

[.net] How to make function that return more than 1 value in Visual C++?

Recommended Posts

Hi I am using Visual C++. Is it possible to make a function that return more than one value? At least they have the same type. For example, I want to get the file name and the file content but both of them of the same type, which is String. I don't know if it is possible or not. If it is possible, how to do that? Please give me a code sample if possible, in C# also no problem. Thank you very much.

Share this post


Link to post
Share on other sites
One simple way would be to make a struct


struct FileInfo
{
std::string name
std::string data
};

FileInfo foo ( ... blah )
{
FileInfo rVal
.. blah ..
return rVal;
}

int main ( )
{
FileInfo data = foo ( ... );
std::cout << data.name << " : " << data.data << std::endl;
}




Just remember that for larger structures, you probably want to allocate on the heap, and return a pointer.

FileInfo *foo ( ... )
{
FileInfo *rVal = new FileInfo;
... blah ...
return rVal;
}

int main ( )
{
FileInfo *data = foo ( ... );
std::cout << data->name << " : " << data->data << std::endl;
delete data;
}


Share this post


Link to post
Share on other sites
If you want to return a number of objects of the same type, you can return a std::vector of them, or something similar.


std::vector< std::string > GetFileNameAndContents()
{
std::vector< std::string > strings;
//fill strings with whatever
return strings;
}

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this