如何访问双指针对象中的方法
How to access method in double pointer object
我有一个简单的示例代码
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,但老实说,对于这种琐碎的情况,我发现显式循环更可读,也就是说,它对我来说更清楚地表明了正在做什么。
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行