如何编写一个数字相加的方法并保存在c++中

How to write a method to add up number and save it in C++

本文关键字:方法 保存 存在 c++ 何编写 数字 一个      更新时间:2023-10-16

我目前正在学习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{
  ...
};