Apologies if this is a basic question, I am new to C++. Let us say I have 2 classes, A and B, defined as below:
class A {
public:
A(int i) { a = i; };
A(A&) = default;
int a;
};
class B {
public:
B(A& a) : this_a(a) {};
B(B&) = default;
A& this_a;
void set_a(A& a) {
this_a = a;
};
};
and let us say my main method is:
int main()
{
A a1(5);
A temp(5);
B e(temp);
cout << a1.a << endl;
e.set_a(a1);
e.this_a.a = 0;
cout << a1.a << endl;
cout << e.this_a.a << endl;
return 0;
}
The output for this code is:
5
5
0
As far as I can tell, this is the output because in my setter, the copy constructor is being used for the A reference being stored in the B object. This is why:
int main()
{
A a1(5);
B e(a1);
cout << a1.a << endl;
e.this_a.a = 0;
cout << a1.a << endl;
return 0;
}
Outputs:
5
0
Is there any way for me to be able to write the setter in such a way that I can still access the member by reference?
Aucun commentaire:
Enregistrer un commentaire