只要在bai两个要声明的类中,分du别将该函zhi数声明为友元函数即可。dao
C++对友元函数属于几个类并没有限制shu,只要在对应类中声明为友元,则该函数即为此类的友元函数。
这个代码只是想说不同的类可以共用一个友元函数。 友元函数可以看成具有特殊访问权限的函数,它本质是函数,所以,在一个类中为友元,当然,也可以在其他类中声明为友元~~
#include<iostream>
using namespace std;
class Boat;//Boat类的声明,如果不声明,Car类里的友元函数声明会找不到Boat
class Car{
public:
Car(int weight){
Car::weight=weight;
}
friend int getToalWeight(Car &c,Boat &b); //友元函数声明
private:
int weight;//Car的weight;
};
class Boat{
public:
Boat(int weight){
Boat::weight=weight;
}
friend int getToalWeight(Car &c,Boat &b); //友元函数声明
private:
int weight;//Boat的weight
};
//友元函数实现,boat和car的weight和
int getToalWeight(Car &c,Boat &b){
return b.weight+c.weight;
}
int main(){
Boat b(300);
Car c(40);
cout<<"总重量为:"<<getToalWeight(c,b)<<endl;
return 0;
}
再如
class A
{
private:
int a;
friend void test();
};
class B
{
private:
int a;
friend void test();
};
如果两个类中用到同一个变量,此时改变了在使用是需要用限定符指定为本类,如
class Car{
public:
Car(int weight){
Car::weight=weight;
}
friend int getToalWeight(Car &c,Boat &b); //友元函数声明
private:
int weight;//Car的weight;
};
class Boat{
public:
Boat(int weight){
Boat::weight=weight;
}
friend int getToalWeight(Car &c,Boat &b); //友元函数声明
private:
int weight;//Boat的weight
};
分别用Boat::weight和Car::weight限定变量为自身的类变量成员.
推荐参考:
https://blog.csdn.net/new_objectc/article/details/51058493