Friend Function

Can anyone tell me what's wrong with it?


#include<cstdlib>
#include<iostream>
using namespace std;
class Patient
{
float Height;
float Weight;
friend class PatientHeightAndWeight;
};
class PatientHeightAndWeight
{
public:
PatientHeightAndWeight(Patient P1)
{
cout << "Please Enter The Patient's Height (In Meters): ";
cin >> P1.Height;
cout << "Please Enter The Patient's Weight (In KG): ";
cin >> P1.Weight;
}
};
class BMI
{
public:
BMI(PatientHeightAndWeight P2)
{
cout << endl << endl;
cout << "Patient Height: " << P2.Height << " Meters." << endl;
cout << "Patient Weight: " << P2.Weight << " Kilograms." << endl;
cout << endl;
cout << "The Patient's BMI (Body Mass Index) is: ";
cout << P2.Weight/(P2.Height*P2.Height) << endl;
}
};
int main()
{
Patient P1;
PatientHeightAndWeight P2(P1);
BMI P3(P2);
system("Pause");
return 0;
}
Last edited on
You must always remember to post the error message that you receive.

I am thinking your problem is that you don't forward-declar ethe class PatientHeightAndWeight.

Also note that you are creating copies of this class whenever you create a class of type BMI. You should change this paramter to take the class as const and by reference.
I'm sorry forgot about that.
It show me error in class BMI. It mention that the height and weight is undeclared.
I wondering that if there is any ways to link three classes together using the friend function.
Thank you.
closed account (zb0S216C)
PatientHeightAndWeight doesn't have any members named Height or Weight. Also, the friend class within Patient is redundant since there're no private members of PatientHeightAndWeight.

Wazzak
Last edited on
This is the error when i run the above code:
`BMI::BMI(PatientHeightAndWeight)':
27 'class PatientHeightAndWeight' has no member named 'Height'
28 'class PatientHeightAndWeight' has no member named 'Weight'
31 'class PatientHeightAndWeight' has no member named 'Weight'
31 'class PatientHeightAndWeight' has no member named 'Height'
31 'class PatientHeightAndWeight' has no member named 'Height'

Do you know how to solve it?
closed account (1vRz3TCk)
If you want a friend function is it not easier to have one rather that a class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

class Patient
{
public:
    Patient(float Height = 1.0, float Weight =1.0)
        : height(Height), weight(Weight)
    {
    }
private:
    float height;
    float weight;
    friend float CalculateBmi(const Patient &);
};

float CalculateBmi(const Patient &p)
{
    return (p.weight / (p.height * p.height));
}

int main()
{
    Patient a(1.88, 105);

    cout << "The Patient's BMI (Body Mass Index) is: " << CalculateBmi(a) << endl;
    
    return 0;
}
Is there any possible solution to solve the problem without changing the number of classes above?
Topic archived. No new replies allowed.