简体   繁体   English

如何创建继承的类对象的数组?

[英]How do I create an array of inherited class objects?

I'm having a bit of trouble working on my current project. 我在当前项目中工作时遇到麻烦。 The project consists of taking lines of data from a file and creating an array of class objects that all inherit a base class. 该项目包括从文件中获取数据行,并创建一个均继承基类的类对象数组。

So, this is what I understand so far: 因此,这是我到目前为止所了解的:

class BaseClass {
    // create empty and non-empty constructor
}

class SubClass : public BaseClass {
    // create constructor specifically for this class 
}

int main() {
    BaseClass *array[size];
    array[index] = new SubClass();

    return 0;
}

Since the SubClass inherits the BaseClass, When I add a new object to the array it should be of type SubClass, correct? 因为SubClass继承了BaseClass,所以当我向数组添加新对象时,它应该是SubClass类型,对吗?

When I debug the program and look at that object, it doesn't allow me to point to any of the SubClass methods/variables for manipulation which is what I need to be able to do. 当我调试程序并查看该对象时,它不允许我指向任何SubClass方法/变量进行操作,而这正是我需要做的。

Now when I was searching for answers I came across static casting, so I tried it to the extent of: 现在,当我在寻找答案时,我遇到了静态转换,因此我尝试了以下程度:

(static_cast<SubClass*>(array[index])->subclass_variable) = some_value

But that doesn't seem to work either, any help with this would be greatly appreciated. 但这似乎也不起作用,对此将提供任何帮助。

One way to handle this is defining an interface (virtual methods) in the base class and implementation in SubClass : 一种解决方法是在基类中定义接口 (虚拟方法),并在SubClass 实现

class BaseClass {
    // create empty and non-empty constructor
    virtual void f() = 0;
}

class SubClass : public BaseClass {
    // create constructor specifically for this class 
    virtual void f() { std::cout << "I am your SubClass" << std::endl; }
}

Then you can call array[index]->f(); 然后可以调用array[index]->f(); .

Another way is visiting / type switching on the class, another is NVI, but those are somewhat more advanced topics. 另一种方法是在类上访问/类型切换,另一种方法是NVI,但这是更高级的主题。

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

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