【发布时间】:2018-08-01 20:45:30
【问题描述】:
不确定我的继承在哪里出错,但我似乎只能在将子类实例存储在基类指针中时访问基类的方法:
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()
}
这很可能是指针的滥用。我承认 C++ 不是我的强项,所以我试图复制一个用 Python 编写的程序,它大量使用继承,但它比用 C++ 编写的程序简单得多,因为你没有明确使用指针和引用(在抽象级别)。
【问题讨论】:
-
您可以在
Car中将get_doors()设为纯虚函数,并在Ford中覆盖它。但是它不能返回void。 -
“抽象类实例化”是什么意思?你不能实例化一个抽象类。
-
是的,您可以使用
Car*指向来自Car的派生类的任何实例。但您也仅限于Car可用的操作。 (因为不能保证你的Car*指向的东西支持get_doors。想象一下如果第二行是c = new Car();。) -
这就是虚函数的用途,正如我在第一条评论中提到的那样。 C++ 是静态类型的,不像 Python 那样具有“鸭子类型”。
-
试试
static_cast<Ford *>(c)->get_doors();