[英]Using array of pointers to object in C++
我需要将对象保存为动态数组中的指针,但我有问题。 这是我的代码,有三个类,我需要有指向第二类的指针数组 (arrayoftwo),这样可以进一步与第三类一起工作,依此类推。 我有两个问题。 一个是我无法弄清楚如何为我的 arrayoftwo 动态分配空间(我需要根据存储的指针数量动态调整大小),第二个问题是如何在不破坏对象本身的情况下准确存储指向对象的指针。 这是我的代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
class One {
public:
bool addTwo(int a);
private:
void getspace(void);
class Two {
public:
int a;
private:
class Three {
/*...*/
};
Three arrayofThree[];
};
int freeindex;
int allocated;
Two *arrayoftwo[];
};
void One::getspace(void){
// how to allocate space for array of pointers ?
arrayoftwo=new *Two[100];
allocated=100;
}
bool One::addTwo(int a){
Two temp;
temp.a=a;
getspace();
arrayoftwo[freeindex]=&temp;
freeindex++;
return true;
//after leaving this method, will the object temp still exist or pointer stored in array would be pointing on nothing ?
}
int main() {
bool status;
One x;
status = x . addTwo(100);
return 0;
}
感谢您的任何帮助。
编辑:我不能使用矢量或任何其他高级容器
离开addTwo
后temp
将不存在; 您存储到它的指针此时无效。 不是将对象存储为局部变量,而是使用 new 在堆上分配它:
Two* temp = new Two();
分配指针数组:
Two** arrayoftwo; // declare it like this
// ...
arrayoftwo = new Two*[100];
并且getspace
应该传递a
(来自addTwo
)或a
应该存储为allocated
的成员变量并且getspace
应该从那里访问它。 否则它假设100
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.