【用友元函数计算Boat和Car类对象的总重量】

【问题描述】定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。

【输入形式】卡车和轮船的重量

【输出形式】卡车和轮船的总重量

【样例输入】

    卡车重量:25

    轮船重量:36

【样例输出】

    卡车和轮船的总重量为:61

【样例说明】
【评分标准】3个评分点

代码如下:有的地方请自行修改

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<istream>
#include<iomanip>
#include<ostream>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<fstream>
#include<stack>
#include<ctime>
#include<deque>
#include<queue>
#include <sstream>
#include <numeric>
#pragma warning (disable:4996)

using namespace std;

// 前向声明
class Boat;

// Car类的定义与实现
class Car {
public:
    Car(int weight) : weight(weight) {}

    // 声明友元函数
    friend int getTotalWeight(Car& aCar, Boat& aBoat);

private:
    int weight;
};

// Boat的定义与实现
class Boat {
public:
    Boat(int weight) : weight(weight) {}

    // 声明友元函数
    friend int getTotalWeight(Car& aCar, Boat& aBoat);

private:
    int weight;
};

// 友元函数getTotalWeight()
int getTotalWeight(Car& aCar, Boat& aBoat) {
    return aCar.weight + aBoat.weight;
}

int main() {
    int carWeight, boatWeight;
    cout << "卡车重量:";
    cin >> carWeight;
    cout << "轮船重量:";
    cin >> boatWeight;
    cout << endl;
    Car aCar(carWeight);
    Boat aBoat(boatWeight);

    int totalWeight = getTotalWeight(aCar, aBoat);
    cout << "卡车和轮船的总重量为:" << totalWeight << endl;

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值