将对象传递到同一父类的数组中
Passing object into array that are of the same parent 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};
}
我试图实现这一点,这样我就可以创建一个使用动态数组的函数来保存对象指针,这样我可以在函数中取消引用它们并相应地操作它们。尽管我在进入数组时遇到了让不同指针协同工作的问题。我需要这样的功能,因为会有很多不同的对象(都在同一个父对象下)进出这个功能。
是的,这是可能的。但是你需要像这个一样声明数组
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;
}
};
相关文章:
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 类数组插入函数
- C++访问指向结构的指针中的类数组指针
- 类数组正在损坏数据
- 如何在 turbo C++ 中增加类数组的大小?
- 如何初始化文件中的文本并将其传递给类数组,以便在c++中输出
- 从基类数组调用派生函数
- lower_bound结构节点的类数组中
- 在构造函数中使用参数创建一个类数组
- 有没有办法拥有一个未初始化的类数组,这些类在调用 delete[] 时不会被破坏?
- 使用泛型成员变量"placement new"结构/类数组的正确方法是什么?
- 如何将字符串片段读入类数组C++
- 如果类数组中的向量是动态push_backed的,内存如何工作
- C 类数组的Kotlin等效
- 指针算术,带有指向类数组的指针
- 具有多种类型的类数组?如何访问数组中的一个类型
- 尝试在类数组上使用成员函数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 存储在父类中的派生类数组
- 调用一个方法在C多个类数组的子,执行父一个