[英]How to return a location as x,y,z
How can I make this return x and y, instead of just one of them? 我怎样才能使返回的x和y而不只是其中之一? In my Location class, I have protected data named
x_pos
and y_pos
. 在Location类中,我保护了名为
x_pos
和y_pos
数据。
void Location::getXY(double& x, double& y) const {
x_pos = x;
y_pos = y;
return x, y;
}
You can return a std::pair
. 您可以返回一个
std::pair
。 I am assuming you want to return by value and not by reference here. 我假设您想按值而不是此处引用返回。
#include <utility> // for std::pair
// if using c++14, else use std::pair<double,double> as return type
auto Location::getXY(double& x, double& y) const {
x_pos = x;
y_pos = y;
return std::make_pair(x,y);
}
Although i must note that this function doesn't make logical sense, you are returning values which you passed to begin with without modifying them. 尽管我必须注意,此函数没有逻辑意义,但是您返回的是传递给它们的值,而无需修改它们。
You've probably meant 你可能是说
void Location::getXY(double& x, double& y) const {
x = x_pos;
y = y_pos;
}
This way you store Location
's internal x_pos
and y_pos
in provided locations. 这样,您将
Location
的内部x_pos
和y_pos
在提供的位置中。 You don't need to return
anything from a function returning void
(actually, you cannot return anything but void
itself). 您不需要从返回
void
的函数return
任何东西(实际上,除了void
本身,您不能返回任何东西)。 As everyone said before, returning an std::pair
might be a better idea. 正如大家之前所说,返回一个
std::pair
可能是一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.