将对象传递到同一父类的数组中

Passing object into array that are of the same parent class

本文关键字:父类 数组 对象      更新时间:2023-10-16

由于我对C++编程还有些陌生,我只是想知道是否可以将对象指针传递到数组以进行代码合并。

类似的头文件;

class.h
class parent
{
    some information.....
};
class child1 : public parent
{
    some information.....
};
class child2 : public parent
{
    some information.....
};

像这样的主文件;

main.cpp
#include "class.h"
int main()
{
    child1 instanceChild1;
    child2 instanceChild2;
    child1* pointer1 = &instanceChild1;
    child2* pointer2 = &instanceChild2;
    parent array[2] = {pointer1 , pointer2};
}

我试图实现这一点,这样我就可以创建一个使用动态数组的函数来保存对象指针,这样我可以在函数中取消引用它们并相应地操作它们。尽管我在进入数组时遇到了让不同指针协同工作的问题。我需要这样的功能,因为会有很多不同的对象(都在同一个父对象下)进出这个功能。

是的,这是可能的。但是你需要像这个一样声明数组

parent * arr[] = { ... }

或者如果你使用矢量会更好

vector<parent *> arr;
arr.push_back(childPointer);//For inserting elements

正如@pstrjds和@basile所写如果你想使用特定于子成员的函数,你可以使用动态转换

ChildType1* ptr = dynamic_cast<ChildType1*>(arr.pop());
if(ptr != 0) {
   // Casting was succesfull !!! now you can use child specific methods
   ptr->doSomething();
}
else //try casting to another child class

**您的编译器应该支持RTTI,以便它能正确工作

你可以看到这个答案的详细信息

我更喜欢使用像这样的纯虚拟功能

class A {   
        public :
        enum TYPES{ one , two ,three };
        virtual int getType() = 0;
    };
class B : public A{
public:
    int getType()
    {
        return two;
    }
};
class C : public A
{
    public:
    int getType()
    {
       return three;
    }
};