I'm trying to call the setter function from Class A
in class B
but I'm unable to do this and I don't know why. (I'm a beginner in C++ and I need to do this as it's related to my assignment.)
Here is my code:
#include <iostream>
using namespace std;
class A{
private:
int i = 2;
public:
int getInt(){
return i;
};
void setI(int a){
i = a;
}
};
class B{
private:
int c = 3;
public:
void setAI(A a){
a.setI(c);
}
};
int main() {
A a;
B b;
cout << a.getInt() << endl;
b.setAI(a);
cout << a.getInt() << endl;
a.setI(5);
cout << a.getInt() << endl;
}
The output I'm getting is:
2
2
5
When I want to get:
2
3
5
I just made some changes in the setAI()
function. I have passed the object by address rather than value. I'm not sure of what was causing the problem (as I'm also a beginner) but the pointer has solved the problem.
#include <iostream>
using namespace std;
class A{
private:
int i = 2;
public:
int getInt(){
return i;
};
void setI(int a){
i = a;
}
};
class B{
private:
int c = 3;
public:
void setAI(A *a){
a->setI(c);
}
};
int main() {
A a;
B b;
cout << a.getInt() << endl;
b.setAI(&a);
cout << a.getInt() << endl;
a.setI(5);
cout << a.getInt() << endl;
}
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.