#include <iostream>
using namespace std;
class calculator {
public:
int n1, n2;
friend void setNumbers(calculator v);
friend void getNumbers(calculator v);
};
void setNumbers(calculator v) {
cin >> v.n1 >> v.n2;
}
void getNumbers(calculator v) {
cout << v.n1 << ' ' << v.n2 << '\n';
}
int main() {
calculator calc;
setNumbers(calc);
getNumbers(calc);
return 0;
}
When I call getNumbers function, it prints totally different values which I didn't input. For example when I input 3 6
, it prints 0 1
, while I expected 3 6
. What could be wrong?
Passing the object without a reference won't change the values of your calculator object when you expect them to be initialized by your input values after a call to setNumbers
. Instead they'll have garbage values since they are not initialized for getNumbers
.
Pass the calculator objects via reference by using &
as mentioned in the comments and you're good to go.
class calculator
{
public:
int n1, n2;
friend void setNumbers(calculator &v);
friend void getNumbers(calculator &v);
};
void setNumbers(calculator &v) {
cin >> v.n1 >> v.n2;
}
void getNumbers(calculator &v) {
cout << v.n1 << ' ' << v.n2 << '\n';
}
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.