如何访问双指针对象中的方法

How to access method in double pointer object

本文关键字:对象 指针 方法 何访问 访问      更新时间:2023-10-16

我有一个简单的示例代码

class Child2{
public:
Child2(){
cout<<"this is child2"<<endl;
}
void test2(){
cout<<"Method Child 2"<<endl;
}
};
class Child1{
public:
Child2 **child2;
Child1(){
child2 = new Child2 *[1];
child2[0] = new Child2();
cout<<"this is child1"<<endl;
}
void test1(){
cout<<"Method Child 1"<<endl;
}
};
class Top{
public:
Child1 **child1;
Top(){
child1 = new Child1 *[2];
child1[0] = new Child1();
child1[1] = new Child1();
cout<<"this is top"<<endl;
}
};

现在,我知道我可以使用访问方法"test2((">

top->child1[0]->child2[0]->test2();

但是,如果我想在不放置数组索引的情况下动态访问该方法,那么可以访问所有"child2"的"test2(("吗。我需要保留双指针,因为我想在运行时使用输入分配对象。

谢谢

没有任何运算符可以神奇地为数组的所有元素调用该方法。

最简单的方法是在数组中的每个项目上使用一个循环:

for(int ndx = 0, count = ...; count != ndx; ++ndx)
child2[ndx]->test();

您也可以使用std::for_each,但老实说,对于这种琐碎的情况,我发现显式循环更可读,也就是说,它对我来说更清楚地表明了正在做什么。