您的位置:首页 > 编程语言 > C语言/C++

友元函数

2013-12-09 13:55 162 查看
定义Boat与Car两个类,二者都有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++ 友元函数