定义两个类共同的友元函数

View Code
#include<iostream>
using namespace std;

class Car;//为了使class Boat中可以定义Car类,可以暂时先声明可以引用Car类
class Boat
{
public:
Boat(
int tBweight=0)
{
Bweight
=tBweight;
}
friend
class Car;
friend
void getTotalWeight(Car &C,Boat &B);//共同友元函数在每个引用的类都要定义
private:
int Bweight;
};

class Car
{
public:
Car(
int tCweight=0)
{
Cweight
=tCweight;
}
friend
class Boat;
friend
void getTotalWeight(Car &C,Boat &B);//共同友元函数在每个引用的类都要定义
private:
int Cweight;
};

void getTotalWeight(Car &C,Boat &B)
{
int all;
all
=B.Bweight+C.Cweight;
cout
<<all<<endl;
}

void main()
{
Boat boat(
1);
Car car(
2);
getTotalWeight(car,boat);
}
原文地址:https://www.cnblogs.com/huhuuu/p/2005238.html