-
数据的保护与共享(1)---用友元函数计算Boat和Car类对象的总重量
2. 【问题描述】定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
【输入形式】卡车和轮船的重量
【输出形式】卡车和轮船的总重量
【样例输入】
卡车重量:25
轮船重量:36
【样例输出】
卡车和轮船的总重量为:61
/*定义Boat与Car两个类,二者都有weight属性, 定义二者的一个友元函数totalWeight(),计算二者的重量和*/ #include <iostream> using namespace std; class Boat; class Car //Car类的定义与实现 { private: int carweight; public: Car(int carweight=0):carweight(carweight){};//构造函数的初始化 Car(Car &aCar) { carweight=aCar.carweight; } int getx(int carweight) { return carweight; } friend int getTotalWeight(Car &aCar,Boat &aBoat); }; //Boat的定义与实现 class Boat { private: int boatweight; public: Boat(int boatweight=0):boatweight(boatweight){};//Boat构造函数的初始化 Boat(Boat &aBoat) { boatweight=aBoat.boatweight; } int gety(int boatweight) { return boatweight; } friend int getTotalWeight(Car &aCar,Boat &aBoat);//友元函数声明 }; //友元函数totalWeight() int getTotalWeight(Car &aCar, Boat &aBoat) { int carweight=aCar.carweight; int boatweight=aBoat.boatweight; return carweight+boatweight; } int main() { int a,b; cout<<"卡车重量"<<": "; cin>>a; cout<<"轮船重量"<<": "; cin>>b; cout<<endl; Car one(a); Boat two(b); cout<<"卡车和轮船的总重量为"<<": "<<getTotalWeight(one,two); return 0; }
c++:实验题3
最新推荐文章于 2022-05-14 17:23:08 发布