In my program (this is only a short version), I have a struct that has 9 members (airplanes) which all have the same variables.
struct FlightP {string FLID; int altitude; int heading; flightMode; } ArrP_1, ArrP_2;//1-9 etc
If I want to change for example the altitude of members ArrP_1 and ArrP_2 I did it like so:
int main(){
ArrP_1.altitude = 10000;
ArrP_2.altitude = 10000;
}
But is there a way to use a function like that:
void ALtChange(FlightP flight_p){
flight_p.altitude = 12000;
}
int main(){
ALtChange(ArrP_1);
ALtChange(ArrP_2);
//If I have to change multiple parameters in multiple members at the same time this function would make things easier.
}
Somewhy this function doesn't do anything. Is the function wrong or what should I do differently?
Somewhy this function doesn't do anything.
Your function modifies the function argument that is local to the function.
In order to modify a variable from another scope, you can use indirection: Use a reference argument.
Instead of modiying the object in the function, another approach is to write a function that returns a ALtChange
object, and you can assign the result to a variable to modify it.
It's like @Jonnhy Mopp said, pass it by reference like so:
#include <iostream>
#include <string>
using namespace std;
struct FlightP {string FLID; int altitude; int heading; int flightMode; } ArrP_1, ArrP_2;//1
void ALtChange(FlightP& flight_p) { flight_p.altitude = 12000; }
void print_altitude(const FlightP& flight) { std::cout << flight.altitude << std::endl; }
int main(){
ArrP_1.altitude = 10000;
ArrP_2.altitude = 10000;
ALtChange(ArrP_1);
ALtChange(ArrP_2);
print_altitude(ArrP_1);
print_altitude(ArrP_2);
}
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.