声明 Book 与 Ruler 两个类,二者都有 weight 属性,定义二者的一个友元函数 totalWeight (),计算二者的重量和。
#include <iostream>
using namespace std;
class ruler;
class book
{
private :
int weight1;
public:
book(int w1)
{
weight1 = w1;
}
void totalweight(ruler& x);
};
class ruler {
private :
int weight2;
public:
ruler(int w2)
{
weight2 = w2;
}
friend void book::totalweight(ruler& x);
};
void book::totalweight(ruler &x)
{
int w=weight1+x.weight2;
cout << "weight1+weight2" << "=" << w << endl;
}
void main()
{
book item1(123);
ruler item2(345);
item1.totalweight(item2);
}