我有这个结构(数组),我想用类对象填充它。完成它的程序是什么?我使用的教程/书籍没有那么详细,我不知道该怎么做。(因为我的尝试失败了)
数组结构 结构.h
struct Arr{
int days;
int *M;
};
typedef Arr* Array;
结构.cpp
void constr(Array &o){
//Construct of 1*31 Matrix
o=new Arr;
o->days = days;
o->M = new int[o->days];
类
exp.h
class Expe {
private:
int *obj;
public:
Expe();
~Expe();
void setObj(int ,int ,int ,int ,int ,int);
void printObj();
int getObj();
enter code here
exp.cpp
Expe::Expe() {
this->obj=new int[6];
}
Expe::~Expe() {
delete this->obj;
}
ps:我需要用自己的struct vector.h是不允许的,必须是dyanmical
最佳答案
就像现在的代码一样,您的 Arr
结构可以保存一个整数数组。如果你想让它保存 Expe
对象,你可以将它定义为:
struct Arr{
int days;
Expe* M;
};
或者,更好的是,让它成为一个模板类:
template<typename T>
struct Arr
{
int _size;
T* M;
};
我还建议将构造函数移动到 inside struct
而不是 constr
方法:
template<typename T>
struct Arr
{
int _size;
T* M;
Arr(int size) : _size(size)
{
M = new T[size];
}
//manage the memory:
~Arr()
{
delete[] M;
}
};
通过使用模板,您可以根据需要专门化 Arr
:
Arr<int> x(10); //creates an array of 10 int's
Arr<Expe> y(10); //creates an array of 10 Expe's
作为旁注,因为这不是 PHP,所以 this->
在类上下文中并不是真正必需的,除非您有一个与成员同名的局部变量,你不知道。
关于c++ - 如何用类对象填充数组结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10113594/