我有一些基本的C++设计/语法问题,非常感谢您的回复.
即我想达到这样的目的:
region[i].elements
=区域i的所有元素的列表.
问题1: 以下语法(请参阅下面的代码)/ design是否正确.我在这里错过了什么吗?
编辑
struct elem的实例是由其他一些类创建的,它的内存释放是该类的处理,我只想使用reg [i] .elements list(vector)访问该对象及其成员......所以,我该怎么办将这些元素对象添加到类Region中的向量"elements"中?
//我已经有了这个需要使用的结构
struct elemt {
int* vertex;
int foo1;
double foo2;
};
class Region{
public:
// I am not sure what should be the syntax here!
// is it correct?
std::vector <elemt*> elements;
}
// Following is the constructor of "class A"
A::A(){
// --header file defines: Region *reg;
// Let numOfRegions be a class variable. ( changes based on "Mac"'s suggestion)
numOfRegions = 100;
//allocate memory:
reg = new Region[numOfRegions];
}
A::~A(){
delete [] reg;
reg = NULL;
}
A::doSomething(){
// here I want to append the elements to the vector
// Let i be region 10.
// Let e1 be an element of "struct elemt" that needs to be added
reg[i].elements.push_back(e1);
}
Run Code Online (Sandbox Code Playgroud)
问题2:
语法doSomething()
是否正确?后来我想在所有元素中运行一个迭代器,reg[i]
并且想要访问,e1->foo1, e1->foo2
就像那样.
问题3: 在做某事的方法中,我如何确保e1不在"元素"中
UPDATE
纠正了一些语法错误,并希望修复用户'Mac注意到的内存泄漏."
首先摆脱代码中的内存泄漏.
A::A(int numOfRegions = 100){
m_reg = new Region[numOfRegions]; // define Region *m_reg in the class
}
A::~A(){
delete [] m_reg;
m_reg = NULL;
}
You are allocating memory in the constructor and storing return address in local variable and it ll get destroyed when its scope is over .
You should store the base address so that you can delete it .
Run Code Online (Sandbox Code Playgroud)