声明Book与Ruler两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。(sy5_3.cpp)
时间: 2023-05-23 19:04:20 浏览: 127
以下是代码示例:
```c++
#include<iostream>
using namespace std;
class Ruler;
class Book{
private:
int weight;
public:
Book(int w): weight(w){}
friend int totalWeight(Book b, Ruler r);
};
class Ruler{
private:
int weight;
public:
Ruler(int w): weight(w){}
friend int totalWeight(Book b, Ruler r);
};
int totalWeight(Book b, Ruler r){
return b.weight + r.weight;
}
int main(){
Book book1(100);
Ruler ruler1(50);
int total = totalWeight(book1, ruler1);
cout<<"Total weight: "<<total<<endl;
return 0;
}
```
此代码定义了类Book和类Ruler,并在二者中分别声明了weight属性。另外,定义了一个名为totalWeight的友元函数,它可以访问类Book和类Ruler的私有成员变量,并返回二者重量之和。
在main函数中,分别创建了名为book1和ruler1的Book对象和Ruler对象,并将它们作为参数传递给totalWeight函数,最终输出了它们的重量总和。