用C++定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class cat;
class Boat;
class Boat
{
private:
int weight;
public:
void getwei(int t)
{
weight=t;
}
friend void getweight(Boat a,cat b); // 定义getweight为友元函数,为后面调用做准备
};
class cat
{
private:
int weight;
public:
void getwei(int t)
{
weight=t;
}
friend void getweight(Boat a,cat b);//如上
};
void getweight(Boat a,cat b)
{
int w=a.weight+b.weight;//由于是getweight是友元函数,所以可以直接调用boat和cat类中的私有成员
printf("%d\n",w);
}
int main()
{
Boat a;
a.getwei(10);
cat b;
b.getwei(5);
getweight(a,b);
return 0;
}
本文通过定义Boat与Car两个类,并设置weight属性,演示了如何使用友元函数totalWeight()来计算两个对象的重量总和。该示例展示了类与友元函数的基本用法。
&spm=1001.2101.3001.5002&articleId=79634760&d=1&t=3&u=f342d3b64a134dd3a8f97924d197f2e3)
3110

被折叠的 条评论
为什么被折叠?



