【问题标题】:What is the appropriate manner to return a struct from a called function to a calling function in C++?将结构从被调用函数返回到 C++ 中的调用函数的适当方式是什么?
【发布时间】:2018-09-22 02:15:50
【问题描述】:

我有一个函数,它接受两个 int 值,进行一些处理,然后将处理后的值以结构的形式返回给调用函数。

以下是我调用的函数:

auto start_end(){
bool cond = false;
int xd = 0;
int yd = 0;
std::cout<<("Please enter a desired x coordinate")<<std::endl;

std::cin>>xd;
while(std::cin.fail()){
   std::cout<<("That is not a valid integer. Please enter a valid x co-ordinate")<<std::endl;
   std::cin.clear();
   std::cin.ignore(256,'\n');
   std::cin>>xd;
   }
   std::cout<<("Please enter a desired y coordinate")<<std::endl;

std::cin>>yd;
while(std::cin.fail()){
   std::cout<<("That is not a valid integer. Please enter a valid y co-ordinate")<<std::endl;
   std::cin.clear();
   std::cin.ignore(256,'\n');
   std::cin>>yd;
   }
struct xy{int x_received; int y_received;};
return xy{xd,yd};
}

在上面的函数start_end()中我们可以看到struct xy返回了两个值xd、yd。

以下是我的调用函数:

int main(int argc, const char * argv[]) {
std::cout <<("A-Star-Algorithm for Project 2 obstacle map")<<std::endl;
int x_start = 0;
int y_start = 0;
int init_point = start_end();


return 0;
}

所以当我尝试将返回值 xd、yd 存储在变量 init_point 中时,我得到了错误:

No viable conversion from 'xy' to 'int'

由于出现此错误,我尝试将接收变量写为 2 索引数组:

int init_point[2] = start_end();

当我尝试这样做时,我收到以下错误:

 Array initializer must be an initializer list

我的确切问题:当在函数 int main() 内部调用函数 start_end() 返回的值 xd 和 yd 时,我必须以什么适当的方式接收它?

【问题讨论】:

    标签: c++ function struct return


    【解决方案1】:

    您需要将您的struct 移动到start_endmain 可以看到的地方:

    struct xy { int x; int y; };
    xy start_end()
    {
        ...
        return { xd, yd };
    }
    int main()
    {
    }
    

    然后您可以使用auto 分配它或使用类型名称xy

    int main()
    {
        auto xy1 = start_end();
        xy xy2 = start_end();
    }
    

    或者您可以使用std::pairstd::tuple

    【讨论】:

    • 请注意,您可以编写和使用auto xy1 = start_end();,即使使用 OP 的结构定义的原始位置。但我相信按照您的建议这样做被认为是更好的风格
    【解决方案2】:

    std::tuple 让您如释重负 (live)

    #include <iostream>
    #include <tuple>
    
    auto start_end() {
      auto x = 1, y = 2;
      return std::make_tuple(x, y);
    }
    
    int main() {
      int x, y;
      std::tie(x, y) = start_end();
      std::cout << x << ' ' << y << std::endl;
    }
    

    【讨论】:

    • 从C++17开始也可以写成auto [x, y] = start_end();
    • @M.M 哇,太棒了!您能否指出一些关于此功能的参考资料(例如 cppref 页面)?
    猜你喜欢
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多