3.21 c++上机实验 友元函数的使用(2)
用C++定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class cat;
class Boat;
class Boat
{
private:
int weight;
public:
void getwei(int t)
{
weight=t;
}
friend void getweight(Boat a,cat b); // 定义getweight为友元函数,为后面调用做准备
};
class cat
{
private:
int weight;
public:
void getwei(int t)
{
weight=t;
}
friend void getweight(Boat a,cat b);//如上
};
void getweight(Boat a,cat b)
{
int w=a.weight+b.weight;//由于是getweight是友元函数,所以可以直接调用boat和cat类中的私有成员
printf("%d\n",w);
}
int main()
{
Boat a;
a.getwei(10);
cat b;
b.getwei(5);
getweight(a,b);
return 0;
}