如何使函数返回多个类型? 我想创建一个名为view的函数,返回视图名称,ID和工资 我能做一个单一的(获取)功能吗?
答案 0 :(得分:3)
您可以返回结构或std::tuple
。
类似的东西:
struct foo
{
std::string Name;
unsingned int ID;
unsigned int salary;
};
foo bar()
{
return {"Smith", 42, 1000};
}
答案 1 :(得分:1)
您可以使函数返回包含这些属性的结构。
struct Foo
{
int value1;
int value2;
};
Foo SomeFunction()
{
Foo f = { 1, 2 };
return f;
}
答案 2 :(得分:1)
您可以使用标准班级std::tuple
。例如
#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string, int, float> f()
{
return std::make_tuple( "Doxim", 1, 3500.00 );
}
int main()
{
auto t = f();
std::cout << std::get<0>( t ) << '\t'
<< std::get<1>( t ) << '\t'
<< std::get<2>( t ) << std::endl;
return 0;
}
输出
Doxim 1 3500
或者
#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string, int, float> f()
{
return std::make_tuple( "Doxim", 1, 3500.00 );
}
enum { NAME, ID, SALARY };
int main()
{
auto t = f();
std::cout << std::get<NAME>( t ) << '\t'
<< std::get<ID>( t ) << '\t'
<< std::get<SALARY>( t ) << std::endl;
return 0;
}
答案 3 :(得分:0)
您有两种选择:
使用输入输出参数或创建包含所需类型的结构/类。