友元函数

定义BoatCar两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。

 

#include<iostream>
using namespace std;
class Car;
class Boat{
public:
Boat(int Weight){
weight1=Weight;
}
friend int getTotalWeight(Boat p1,Car p2);
private:
int weight1;
};
class Car{
public:
Car(int Weight){
weight2=Weight;
}
friend int getTotalWeight(Boat p1,Car p2){
return p1.weight1+p2.weight2;
}
private:
int weight2;
};
int main(){
Boat myboat(100);
Car mycar(200);
cout<<"The total weight is "<<getTotalWeight(myboat,mycar)<<endl;
return 0;
}

 

你可能感兴趣的:(c/c++,友元函数)