将对象传递到具有相同父类的数组中

时间:2013-12-06 06:21:40

标签: c++ arrays object pointers base-class

由于我对使用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};
}

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

1 个答案:

答案 0 :(得分:0)

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

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才能使其正常工作

you can see this answer for details

我更喜欢使用像这样的纯虚函数

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;
    }
};