定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。
#include<iostream>
using namespace std;
class Car; //前向引用声明
class Boat
{
public:
Boat(float weight=100):weight(weight){}
float getW() {return weight;}
friend float getTotalWeight(Boat &a,Car &b); //友元函数
private:
float weight;
};
class Car
{
public:
Car(float weight=200):weight(weight){}
float getW() {return weight;}
friend float getTotalWeight(Boat &a,Car &b); //友元函数
private:
float weight;
};
float getTotalWeight(Boat &a,Car &b) //友元函数的实现
{
float sum=a.weight+b.weight;
return sum;
}
int main()
{
Boat a(100);
Car b(150);
cout<<"The sum of weight is:"<<endl;
cout<<getTotalWeight(a,b)<<endl;
return 0;
}