是否可以在一个类中包含另一个类的类对象数组

Is it possible to have a class with an array of class objects from another class inside?

本文关键字:包含 另一个 数组 对象 一个 是否      更新时间:2023-10-16

我有一个名为Regions的类,另一个类我将称为Area。在主类Area中,我需要一个Region类对象的数组。

这是我所在地区的班级:

class Region 
{
public:
    // Constructor
    Region();
    // Get/set functions
    bool getPoly()              {return poly;}
    bool setPoly(bool value)    {poly = value;}
    long getMesh()              {return mesh;}
    void setMesh(long value)    {mesh = value;}
    long getVisibleNum()        {return visibleNum;}
    void setVisibleNum(long value)  {visibleNum = value;}
    // Visibility vector
    void reserveSpace();
    long addVisibleRegion(int region);
    long getSize(){return visibility.size();}
    friend class Area;
private:
    bool poly;          // Does the region have polygons?
    long mesh;          // The reference to a 0x36 mesh
    long visibleNum;    // The number of visible regions
};

现在在我的区域课上,我试图声明这样的东西:

class Area
{
public: // Some public class functions
private:
Region* regionArray; // this should be pointers to an array of class objects
}

在Area类构造函数中,我将分配我想要的类对象的数量。

我得到这个错误:

error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int

所以我认为我没有正确设置它。当Region是一个结构时,它工作得很好,但现在它是一个类,我认为我做错了什么。

是的,这是可能的-你在同一个文件中定义了这些类吗?听起来它们可能在单独的文件中,并且您还没有在Area文件中包含Region的头文件。

编辑:此外,您对Region中的数据有getter函数,因此不需要使Area成为Region的朋友。我也会用std::vector<Region> regionArray替换Region* regionArray,所以内存都是为我管理的。

在我看来,问题在于您引用了一个尚未定义的类。这就是Area类中的:Region* regionArray;行。

如果是这种情况,您必须记住在包含Area类的头文件中包含包含Region类的头。或者在Area类之上添加class Region;

是的,这是可能的。在您的情况下,问题不在于数组。但是(很可能)您没有在其他文件中包含一些头文件。

顺便说一下,您也可以使用std::vector,在我看来,与原始指针相比,这将是一个更好的选择。

#include <vector>
#include "Region.h" //must include these two
class Area
{
  public: // Some public class functions
  private:
  std::vector<Region> regions;  //better than raw pointer
};

阅读RAII习语:资源获取是初始化

其他常见问题是类内的friend class Area;声明首先没有前向声明(我几乎可以肯定是这样,你在使用GCC吗?)

在区域.h

class Area;  // <- this is a forward declaration
clasee Region {
 ...
 friend class Area;
};

问候