是否可以在一个类中包含另一个类的类对象数组
Is it possible to have a class with an array of class objects from another class inside?
我有一个名为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;
};
问候
相关文章:
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 创建一个 const std::vector ,其中包含另一个 const std::vector 和其他值
- 如何为包含另一个类实例的数组制作常量 getter?
- 使用按位运算确定值是否包含另一个值
- 如何在我的 cmake 项目中包含另一个 cmake 项目的头文件?
- 如何查找哪个标头在包含树中包含另一个标头
- 包含另一个实例的特征实例,该实例持有固定大小的特征对象
- 包含另一个对象的对象,然后将其传递给它(C )
- C++初始化包含另一个对象设计问题的对象
- 程序检查是否包含另一个数字
- 包含另一个对象指针向量的对象
- 当动态创建一个包含另一个动态创建的结构数组的结构数组时,内存管理
- BITWISE-如何检查二进制号是否包含另一个数字
- 包含另一个关键部分的关键部分
- 向量emplace_back包含另一个向量(部分向量)的用法(C++11)
- 在我的 qmake 项目中包含另一个项目的 qmake 文件
- 分配包含另一个结构数组的结构数组时出错
- 检查一个文档是否包含另一个c++的内容
- 检查map<string,string>是否包含另一个map<string,string>
- 将包含另一个向量的结构向量写入二进制文件