我正在尝试编写一个函数parkVehicle(),该函数必须通过基类指针访问派生类的读取成员函数。如何访问?
class Parking {
const int MAX_SPOTS_NO = 100;
Base B[MAX_SPOTS_NO];
void parkVehicle() const;
}
class Base : public Read {
std::istream& read(std::istream& istr = std::cin);
}
class derived : public Base {
std::istream& read(std::istream& istr = std::cin);
}
class Read{
virtual std::istream& read(std::istream& istr = std::cin) = 0;
}
void parkVehicle() {
//call read from the derived class
}
如评论中所建议,您的班级设计需要修改。但是,只需摇一晃即可答复您的查询,就可以像这样进行修改-变量MAX_SPOTS_NO需要声明为静态,而成员变量B可以声明为指针数组(而不是使用智能指针),以避免循环冗余问题
class Base; // forward declaration
class Parking {
public:
static const int MAX_SPOTS_NO = 100;
Base* B[MAX_SPOTS_NO];
void parkVehicle() ;
};
void Parking::parkVehicle() {
//call read from the derived class
B[0] = new Base();
B[0]->read();
}