简体   繁体   English

涉及类和结构的构造函数/析构函数

[英]Constructor/Destructor involving a class and a struct

I am working on a program and need to make an array of objects, specifically I have a 31x1 array where each position is an object, (each object is basically built out of 6 ints). 我正在开发一个程序,需要创建一个对象数组,特别是我有一个31x1数组,其中每个位置都是一个对象(每个对象基本上都由6个整数组成)。 Here is what I have but something is wrong and i could use some help thank you. 这是我所拥有的,但是出了点问题,我可以使用一些帮助谢谢您。

31x1 struct header" 31x1 struct header”

const int days=31;

struct Arr{

    int days;
    int *M;
};
typedef Arr* Array;

31x1 matrix constructor: 31x1矩阵构造函数:

void constr(){
    int *M;
    M = new Expe[31]; // Expe is the class 

class header: 类头:

class Expe {
private:
    //0-HouseKeeping, 1-Food, 2-Transport, 3-Clothing, 4-TelNet, 5-others
    int *obj;
}

Class object constructor: 类对象的构造函数:

Expe::Expe() {
    this->obj=new int[6];
}

help please... because i`m pretty lost. 请帮助...因为我很迷路。

You should not use new unless you have to. 除非必须,否则不应使用new You're dynamically allocating memory which you have to manually delete afterwards. 您正在动态分配必须随后手动删除的内存。

Instead, use statically allocated arrays: 而是使用静态分配的数组:

struct Arr{
    int days;
    Expe M[31];
}

This way you don't need to construct M, it automatically is filled with 31 Expe objects. 这样,您无需构造M,它会自动填充31个Expe对象。 Same goes for the int array in Expe. Expe中的int数组也是如此。

(Hint: structs and classes are almost identical. They only difference is that default visibility for structs is public. Apart from that, structs can have member functions and constructors just like classes do.) (提示:结构和类几乎相同。它们的唯一区别是结构的默认可见性是公共的。除此之外,结构可以像类一样具有成员函数和构造函数。)

If you have to use dynamic allocation you should follow this notation: 如果必须使用动态分配,则应遵循以下标记:

X* variableName = new X[size];
...
delete[] variableName; //Be sure to get rid of unused memory afterwards.

Pointers should only be of type int* if you want to store an array of ints in it. 如果要在其中存储一个int数组,则指针的类型只能是int*

You can also use const int s for array size declarations. 您也可以将const int s用于数组大小声明。 So this is valid: 所以这是有效的:

const int size = 5;
int X[size];

You can use this to get rid of the "magic numbers" in your code. 您可以使用它来消除代码中的“幻数”。

Typedefs like typedef Arr* Array; typedef Arr* Array;这样的typedef Arr* Array; are typically used in C, not in C++ so much. 通常在C中使用,而不是在C ++中使用。 There is hardly any situation where you would need to typedef something like this. 在几乎没有任何情况下,您需要键入类似这样的内容。

If you post your entire code we might provide better help. 如果您发布整个代码,我们可能会提供更好的帮助。 It seems that you don't only have one or two errors in your code, but also some fundamental understanding. 看来您的代码中不仅有一个或两个错误,而且还有一些基本的理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM