C++
类,友元
声明Book与Ruler两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
#include<iostream>
using namespace std;
class Ruler;
class Book
{
private:
int weight1;
friend void totalWeight(Book &b,Ruler &r);
public:
void init();
};
void Book::init()
{
cout<<"请输入书的重量:"<<endl;
cin>>weight1;
}
class Ruler
{
private:
int weight2;
friend void totalWeight(Book &b,Ruler &r);
public:
void init();
};
void Ruler::init()
{
cout<<"请输入尺子的重量:"<<endl;
cin>>weight2;
}
void totalWeight(Book &b,Ruler &r)
{
cout<<"二者的重量和为:"<<b.weight1+r.weight2<<endl;
}
int main()
{
Book book;
Ruler ruler;
book.init();
ruler.init();
totalWeight(book,ruler);
return 0;
}