| friends/situation-5/friends-sit5.cc - A variant were we want ma to be a friend of B and mb to be friend of A - problems in this version. | Lecture 4 - slide 34 : 40 Program 4 |
// A version were we would like that a *specific member function* of A gets access
// to the private members in B. And symmetrically, the other way around.
// The symmetric case, where a member function of B gets access to private members in A,
// is not easy to deal with.
// Therefore class B as such is a friend of A in this version.
#include <iostream>
#include <string>
class B;
class A{
private:
double a;
public:
friend class B;
//friend void B::mb(A &x); // invalid use of incomplete type struct B.
// mb in B is unknown at this location in the source file.
A(double a):a(a){}
void ma(B &x);
void print(){
std::cout << a << std::endl;
}
};
class B{
private:
double b;
public:
friend void A::ma(B &x); // ma of class A get access to
// private parts of B.
B(double b):b(b){}
void mb(A &x);
void print(){
std::cout << b << std::endl;
}
};
void A::ma(B &x){
a += x.b;
}
void B::mb(A &x){
b += x.a;
}
int main(){
A aObj(1);
B bObj(2);
aObj.ma(bObj);
bObj.mb(aObj);
aObj.print(); // 3
bObj.print(); // 5
}