c++ - 如何用类对象填充数组结构?

标签 c++ oop

我有这个结构(数组),我想用类对象填充它。完成它的程序是什么?我使用的教程/书籍没有那么详细,我不知道该怎么做。(因为我的尝试失败了)

数组结构 结构.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/

相关文章:

c++ - 添加复数时出错

PHP 和 Mysqli OOP - 处理数据库

php - 如何在接口(interface)文档中记录@throws

c++ - 生成导出包含 ATL::CString 成员的类的 DLL 时出现警告 C4251

c++ - Shared_ptr实现

c++ - googletest参数化的高级使用

c++ - std::make_unique 导致大幅减速?

java:确保该类型只有一个实例

php - 将 mysqli 与 oop php 一起使用

javascript - JS : is it possible to define getter functions on array members?