简体   繁体   English

从具有固定数组大小的基本 class 指针访问派生的 class

[英]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. 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. How can I access it?我怎样才能访问它?

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
}

As suggested in the comments, your class design needs to be revised.正如评论中所建议的,您的 class 设计需要修改。 However, just for the shake of answering to your queries, you can modify like so - variable MAX_SPOTS_NO needs to be declared as static and the member variable B may be declared as pointer array ( prefer to use smart pointers instead) to avoid cyclic redundancy issue但是,只是为了回答您的查询,您可以像这样修改 - 变量 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();
}

Your array is slicing the objects , so there are no derived objects in the array, only Base objects.您的数组正在切片 objects ,因此数组中没有derived对象,只有Base对象。 Polymorphism works only when accessing objects via a pointer or a reference, so you need to change your array to hold Base* pointers:多态性仅在通过指针或引用访问对象时有效,因此您需要更改数组以保存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();
    ...
}

Then you can store derived objects in the array as needed, eg 1 :然后您可以根据需要将derived对象存储在数组中,例如1

derived *d = new derived;
B[index] = d;

Or:或者:

derived d;
B[index] = &d;

1: You did not provide enough of your code to show you exactly HOW you should best create, manage, and store your derived objects. 1:您没有提供足够的代码来准确地向您展示您应该如何最好地创建、管理和存储您的derived对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM