[英]Accessing derived class from base class pointer with a fixed array size
I'm trying to write a function parkVehicle(), this function has to access the read member function of the derived class through a Base class pointer. 我怎样才能访问它?
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
}
正如评论中所建议的,您的 class 设计需要修改。 但是,只是为了回答您的查询,您可以像这样修改 - 变量 MAX_SPOTS_NO 需要声明为 static 并且成员变量 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();
}
您的数组正在切片 objects ,因此数组中没有derived
对象,只有Base
对象。 多态性仅在通过指针或引用访问对象时有效,因此您需要更改数组以保存Base*
指针:
class Parking {
static const int MAX_SPOTS_NO = 100;
Base* B[MAX_SPOTS_NO];
void parkVehicle() const;
};
void parkVehicle() {
//call read from the derived class
...
B[index]->read();
...
}
然后您可以根据需要将derived
对象存储在数组中,例如1 :
derived *d = new derived;
B[index] = d;
或者:
derived d;
B[index] = &d;
1:您没有提供足够的代码来准确地向您展示您应该如何最好地创建、管理和存储您的derived
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.