【问题标题】:Passing object into array that are of the same parent class将对象传递到相同父类的数组中
【发布时间】:2013-12-06 06:21:39
【问题描述】:

由于我对 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* array[2]={pointer1,pointer2};
  • 不知道你在做什么,我建议std::vector<parent*> 而不是创建一个动态数组。您可以通过这种方式将项目添加到向量中 vecParents.push_back(&instanceChild1)
  • 另一件需要注意的事情,如果你将派生对象作为基类对象传递,slicing problem
  • @pstrjds 如果 A 是抽象的,切片问题会不存在吗?
  • @remyabel 你是对的,如果基类是抽象的,那么就不会有切片问题。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多