用C++写代码:重新编写下述程序,使函数 Leisure()成为类 Car 和类 Boat的函数。作为重新编程在类Car 和类 Boat中,增加函数 get()。#include<iostream> using namespace std; class Boat; class Car { public: Car(int j){size = j;} friend int Leisure(int time, Car& aobj, Boat& bobj); protected: int size; }; class Boat { public: Boat(int j){size = j;} friend int Leisure(int time, Car& aobj, Boat& bobj); protected: int size; }; int Leisure(int time, Car& aobj, Boat& bobj) { return time * aobj.size * bobj.size; } int main() { Car cl(2); Boat bl(3); int time = 4; cout<<Leisure(time,cl,bl); }
时间: 2024-03-03 22:46:59 浏览: 311
如何使用C++语言编程
3星 · 编辑精心推荐
以下是重新编写后的代码:
```c++
#include<iostream>
using namespace std;
class Boat;
class Car {
public:
Car(int j){size = j;}
int get() {return size;}
friend int Leisure(int time, Car& aobj, Boat& bobj);
protected:
int size;
};
class Boat {
public:
Boat(int j){size = j;}
int get() {return size;}
friend int Leisure(int time, Car& aobj, Boat& bobj);
protected:
int size;
};
int Leisure(int time, Car& aobj, Boat& bobj) {
return time * aobj.get() * bobj.get();
}
int main() {
Car cl(2);
Boat bl(3);
int time = 4;
cout<<Leisure(time,cl,bl);
}
```
在这个代码中,我们将Leisure函数变成了Car和Boat类的成员函数,并且增加了get函数来获取size属性的值。在Leisure函数中,我们调用了Car和Boat的get函数来获取它们的size属性,然后进行计算并返回结果。最后在main函数中,我们创建了一个Car对象cl和一个Boat对象bl,并将它们作为参数传递给Leisure函数来计算。
阅读全文