无法从基类指针访问子类方法

pst*_*tix 0 c++ c++11

不确定我的继承在这里出了问题,但我似乎只能在将子类实例存储在基类指针中时才能访问基类的方法:

class Car
{
    public:
        Car():type("Car") {};
        Car(const char* t):type(t) {};
        void get_type() const { return this->type; };
    private:
        std::string type;
};

class Ford : public Car
{
    public:
        Ford():Car("Ford"), doors(4) {};
        Ford(int x):Car("Ford"), doors(x) {};
        void get_doors() const { return this->doors; };
    private:
        int doors;
};

int main()
{
    Car* c = nullptr;
    c = new Ford();
    c->get_doors(); // doesn't exist, only allows for get_type()
}
Run Code Online (Sandbox Code Playgroud)

这很可能是指针的误用。我承认 C++ 不是我的强项,所以我试图复制一个用 Python 编写的程序,该程序大量使用继承,但它比用 C++ 编写要简单得多,因为您没有显式使用指针和引用(在抽象级别是)。

dav*_*bak 5

Python 方法是动态的——本质上是纯面向对象的。您向一个实例发送一条消息,如果它可以回复,它就会回复。

C++ 不是这样的。它使用静态类型。你已经声明了一个类型的对象Car*,因此a)它可以保存指向任何Car实例或子类型的实例的指针Car,b)它只能被告知做Cars可以被告知做的事情。

C++也有方法。如果在 中声明的方法Car是虚拟的,那么它可以在 的子类中实现Car(例如,在 中Ford)。然后,当通过指针调用时,将调用该子类的实现Car