【问题描述】定义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;
}