如何编写一个数字相加的方法并保存在c++中
How to write a method to add up number and save it in C++
我目前正在学习c++,有一些关于加法的问题。下面是代码,最终结果应该是这样的:图片请帮我弄明白。否则,我就下地狱了。
#include <iostream>
using namespace std;
/* These three mothod need to be complete and achieve goal
class Vehicle{};
class Truck : public Vehicle{};
class RiverBarge : public Vehicle{};
*/
void main(){
Vehicle *x;
x = new Truck(1000);
Vehicle *y;
y = new RiverBarge(1000);
int a;
double b;
while(true){
cout<<endl<<"Add load to ";
cout<<"(1 for truck, 2 for river barge, & 0 to end): ";
cin>>a;
if( a == 0 )
break;
if( a == 1 ){
x->welcome();
x->details();
} else{
y->welcome();
y->details();
}
cout<<"How many kg: ";
cin>>b;
if( a == 1 ){
x->addBox(b);
} else{
y->addBox(b);
}
}
cout<<endl<<endl<<"END!"<<endl<<"Truck: ";
x->details();
cout<<"River barge: ";
y->details();
system("PAUSE");
}
您需要实现用于类的方法。Vehicle需要纯虚方法,以确保Truck和RiverBarge的方法被调用。
class Vehicle{
public:
Vehicle(int canHold) : maxWeight(canHold), actualWeight(0)
{
}
void welcome() = 0;
void details(){
cout << "the max weight: " << maxWeight << " the actual: " << actualWeight << endl;
}
void addBox(int weight){
// check that weight < max weight, if so add it to actual weight
if (actualWeight + weight <= maxWeight){
actualWeight += weight;
cout << "loaded" << endl;
} else {cout << "too heavy" << endl;}
}
protected:
int maxWeight, actualWeight;
};
class Truck : public Vehicle {
public:
Truck(int canHold) : Vehicle(canHold)
{
}
void welcome(){
//print welcome message
}
};
class RiverBarge : public Vehicle {
public:
RiverBarge(int canHold) : Vehicle(canHold)
{
}
void welcome(){
//print welcome message
}
};
填写缺失部分:
class Vehicle{
float max_load;
float current_load;
public:
Vehicle(the_max_load): max_load(the_max_load), current_load(0.0) {}
void welcome() const = 0;
void details() const {
cout<< ... <<endl;
}
void addBox(float load) {
...
}
};
class Truck : public Vehicle{
public:
Truck(float the_max_load): Vehicle(the_max_load) {}
void welcome() const {
...
}
};
class RiverBarge : public Vehicle{
...
};
相关文章:
- 如何访问由共享指针保存的类方法?
- 优雅和最短的方法,只保存一半的字节
- 如何在C++中使用 void* 在指针作为对方法的引用传递时保存uint32_t的值
- 让类方法为每个实例保存不同的静态变量
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- 如何调用返回双精度或字符串并将其保存在地图上但作为对象的类的方法
- 在模型中保存整数的方法,与QStyledItemDelegate兼容
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 如何在-120到120之间更改int到char(或其他简单保存为一个字节的简单方法)
- C++保存大型数组的最佳方法
- C++:保存特定实例中的方法的函数指针
- 从C++模拟中保存和加载数据的有效方法
- POCO - 属性文件配置保存方法始终使用 ":" 作为分隔符进行写入
- 保存“编辑控件”用户输入并在应用程序重新启动C++Visual Studio时进行恢复的有效方法
- 在实时系统上保存缓存数据的最佳方法是什么
- 方法,该方法调用所有基类的同名方法(如果存在),并将返回值保存到列表中
- 保存一组整数的最佳方法
- C++不会通过其他方法保存更改
- IPersistFile::Save方法始终无法保存快捷方式
- 覆盖保存文件的非常安全的方法