初始化类中的指针数组,并在另一个类中检索它

Initialize array of pointers in a class and retrieve it in a different one

本文关键字:另一个 检索 数组 指针 初始化      更新时间:2023-10-16

我想初始化文件中的指针数组,array.cpp,并在不同的main.cpp中检索它。

我现在有六个标头/src 文件:parent.h/cppchildA.h/cppchildB.h/cpp

class Parent(){
public:
Parent();
virtual void sayHi() = 0;
};
Parent::Parent() {}
class ChildA : Parent{
public:
ChildA()
void sayHi();
ChildA::ChildA()
void ChildA::sayHi(){
std::cout << "Hello A!"
}
class ChildB : Parent{
public:
ChildB()
void sayHi();
ChildB::ChildB()
void ChildB::sayHi(){
std::cout << "Hello B!"
}

我了解如何在main.cpp类中创建包含ChildA()ChildB()的指针数组:

Parent *children[3] = {new ChildA(), new ChildB(), new ChildA()}

如果我想在不同的文件中初始化它,比如array.cpp,然后从main.cpp中检索它怎么办?

我的想法(不起作用(

我的粗略想法是在array.h/cpp中创建定义一个类,如下所示:

class Array(){
Array();
Parent *get_array();    // I don't know how to define it as an array of pointers
}
Array::Array()
Parent *Array::get_array() {
Parent *array[] = { new ChildA(), new ChildB(), new Child() };
return *array;
}

main.cpp

Array array;
Parent *children[] = array.get_array();    // It cannot be initialized like this

这行不通,我不知道如何从这里开始。

只需使用std::vector而不是 C 数组:

class Array
{
public:
Array() {}
std::vector<Parent*> get_array();   
};
std::vector<Parent*> Array::get_array() {
return { new ChildA(), new ChildB(), new Child() };
}
int main()
{
Array a;
std::vector<Parent*> res = a.get_array();
res[0]->sayHi();
res[1]->sayHi();
res[2]->sayHi();
return 0;
}