【问题标题】:Can i make a function return more than one type? [duplicate]我可以让一个函数返回一种以上的类型吗? [复制]
【发布时间】:2014-08-04 17:23:51
【问题描述】:

如何让函数返回多种类型? 我想创建一个名为 view 的函数,它返回视图名称、ID 和薪水 我可以制作一个单独的(获取)函数吗?

【问题讨论】:

  • 请不要让投反对票和不可避免地结束您的问题表明 SO 上的每个人都对新用户怀有敌意。不过,快速谷歌或搜索会回答你的问题。这就是他们这样做的原因。
  • at least 三个different 问题on SO 处理来自C++ 函数的多个返回。如果他们都没有回答您的问题,那么您需要清楚地解释为什么您的问题不同。

标签: c++ oop


【解决方案1】:

您可以返回一个结构或std::tuple

类似:

struct foo
{
    std::string Name;
    unsingned int ID;
    unsigned int salary;
};

foo bar()
{
    return {"Smith", 42, 1000};
}

【讨论】:

    【解决方案2】:

    您可以使用标准类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】:

      您可以让函数返回包含这些属性的结构。

      struct Foo
      {
       int value1;
       int value2;
      };
      
      Foo SomeFunction()
      {
      Foo f = { 1, 2 };
      return f;
      }
      

      【讨论】:

        【解决方案4】:

        你有两个选择:

        要么使用 in-out 参数,要么创建一个包含您需要的所有类型的结构/类。

        【讨论】:

          猜你喜欢
          • 2021-04-16
          • 1970-01-01
          • 1970-01-01
          • 2018-08-01
          • 1970-01-01
          • 2011-02-04
          • 1970-01-01
          • 2017-05-21
          • 1970-01-01
          相关资源
          最近更新 更多