简体   繁体   中英

How to return a location as x,y,z

How can I make this return x and y, instead of just one of them? In my Location class, I have protected data named x_pos and 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 . 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. You don't need to return anything from a function returning void (actually, you cannot return anything but void itself). As everyone said before, returning an std::pair might be a better idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM