#include<iostream.h>
class car;
class boat
{
public:
boat(double bw):bw(0){}
void setbw(double );
friend void totalweight(boat &a,car & b);
private:
double bw;
};
class car
{
public:
car(double cw):cw(0){}
void setcw(double );
friend void totalweight(boat &a,car & b);
private:
double cw;
};
void boat::setbw(double x)
{
bw=x;
}
void car::setcw(double y)
{
cw=y;
}
void totalweight(boat &a,car & b)
{
cout<<"output the total weight of the boat and the car "<<a.bw+b.cw<<endl;
}
void main()
{
double cw,bw;
boat b(20);
car m(10);
totalweight(b,m);
cout<<"input the boat weight"<<endl;
cin>>bw;
b.setbw(bw);
cout<<"input the car weight"<<endl;
cin>>cw;
m.setcw(cw);
totalweight(b,m);
}
熟悉友元函数的使用。
本文通过一个具体的示例,展示了如何定义和使用友元函数来访问两个不同类中的私有成员变量,并实现计算这两个对象的总重量。代码中包含了类定义、成员函数设置权重以及友元函数计算总重量的过程。

被折叠的 条评论
为什么被折叠?



