| friends/situation-3/friends-sit3.cc - Class A and B are mutual friends of each other - this version is OK. | Lecture 4 - slide 34 : 40 Program 3 |
// Solution to the problem in the previous example.
// Class A and B are mutual friends of each other. A member function
// in each class uses a private variable in the other.
// It is important that the member functions ma and mb are defined
// after both classes.
#include <iostream>
#include <string>
class B;
class A{
private:
double a;
public:
friend class B;
A(double a):a(a){}
void ma(B &x);
void print(){
std::cout << a << std::endl;
}
};
class B{
private:
double b;
public:
friend class A;
B(double b):b(b){}
void mb(A &x);
void print(){
std::cout << b << std::endl;
}
};
void A::ma(B &x){ // Member functions must be defined outside the
a += x.b; // classes
}
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
}