[英]Using array of pointers to object in C++
I need to save objects as pointers in dynamic array but i have problem.我需要将对象保存为动态数组中的指针,但我有问题。 This is my code, there are three classes and i need to have array (arrayoftwo) of poiters to class Two that would work further with class Three and so on.
这是我的代码,有三个类,我需要有指向第二类的指针数组 (arrayoftwo),这样可以进一步与第三类一起工作,依此类推。 I have two problems.
我有两个问题。 One is that i cant figure out how to dynamically allocate space for my arrayoftwo (which i need to dynamically resize by number of stored pointers) and second problem is how to exactly store pointers to objects without destroying object itself.
一个是我无法弄清楚如何为我的 arrayoftwo 动态分配空间(我需要根据存储的指针数量动态调整大小),第二个问题是如何在不破坏对象本身的情况下准确存储指向对象的指针。 Here is my code:
这是我的代码:
#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;
}
Thank you for any help.感谢您的任何帮助。
EDIT: I cant use vector or any other advanced containers编辑:我不能使用矢量或任何其他高级容器
temp
will not exist after leaving addTwo
;离开
addTwo
后temp
将不存在; the pointer you store to it is invalid at that point.您存储到它的指针此时无效。 Instead of storing the object as a local variable, allocate it on the heap with new:
不是将对象存储为局部变量,而是使用 new 在堆上分配它:
Two* temp = new Two();
To allocate an array of pointers:分配指针数组:
Two** arrayoftwo; // declare it like this
// ...
arrayoftwo = new Two*[100];
And getspace
should either be passed a
(from addTwo
) or a
should be stored as the member variable allocated
and getspace
should access it from there.并且
getspace
应该传递a
(来自addTwo
)或a
应该存储为allocated
的成员变量并且getspace
应该从那里访问它。 Otherwise it's assuming 100
.否则它假设
100
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.