在C ++中分配抽象类类型的对象

时间:2017-03-22 03:50:21

标签: c++ inheritance vector abstract-class subclass

我现在正在学习继承和指针,但是当我尝试运行一个简单的例子时,显示出错误。这是我的代码。

class car {
public:
    double getKM();
    void setKM(double kIn);

protected: 
   double miles;
   double km;
   virtual void convertMtoKM(double mIn) = 0;
};

class hybirdCar : public car {
public:
     hybirdCar(double a);
private:
     virtual void convertMtoKM(double mIn) override;
};

class electricCar : public car{
public:
     electricCar(double a);
private:
    virtual void convertMtoKM(double mIn) override;
};

我创建了一个名为car的类,并且有两个子类,分别是hybirdCar和electricCar,并尝试从父实现抽象方法。

car:: car(){
    miles = 150;
}
double car::getKM() {
    return km;
}
void car:: setKM(double mIn){
    miles = mIn;
    if (mIn < 0) {
        miles = 0;
    }
    convertMtoKM(miles);
}

hybirdCar::hybirdCar(double a): car() {
    setKM(a);
}
void hybirdCar::convertMtoKM(double mIn) {
    km = (mIn*1.60934);
}

electricCar::electricCar(double a): car() {
    setKM(a);
}
void electricCar::convertMtoKM(double mIn) {
    km = (mIn*1.60934);
}

这是主要方法

#include <stdio.h>
#include <iostream>
#include <memory>
#include <vector>
int main () {
 vector<unique_ptr<car>> my_cars;
    my_cars.push_back(make_unique<hybirdCar>(100));
    my_cars.push_back(make_unique<electricCar>(60)); // shows an error like allocating an object of abstract class type 'electricCar' here
    my_cars.push_back(make_unique<hybirdCar>(80));

    for (int i = 0; i < my_cars.size(); ++i) {
        cout << "Car " << i+1 << endl;
        cout << my_cars[i]->getKM()<< endl;
    }
    return 0;
}

任何人都可以帮我搞清楚吗?我搜索了一些合理的错误原因,但我很确定我正确地实现了抽象方法。

0 个答案:

没有答案