在类中声明动态结构和无符号字符数组的正确方式是什么?
#define GENDER_MALE 0
#define GENDER_FEMALE 1
class c_House {
public:
c_House();
c_House( unsigned int in_BedRoomCount,
short in_FloorCount,
const char* in_Address,
unsigned int in_PeopleCount ) :
BedRoomCount( in_BedRoomCount ),
FloorCount( in_FloorCount ),
Address( in_Address ),
PeopleCount( in_PeopleCount )
{
this->Array = new unsigned char[ in_BedRoomCount ];
this->People = new PEOPLE[ in_PeopleCount ];
};
~c_House() { delete[] this->Array; };
// PROPERTIES
private:
struct PERSON {
unsigned short Age;
const char* Name;
unsigned short Gender;
};
unsigned int BedRoomCount;
short FloorCount;
const char* Address;
unsigned char* Array;
unsigned int PeopleCount;
PERSON *People;
// ACTIONS
private:
void OpenGarage( bool in_Open );
void Vacuum();
};我应该如何声明一个动态数组(int和struct)?我知道这将是非常危险的--考虑深度复制等等:
this->Array = new unsigned char[ in_BedRoomCount ];
this->People = new PEOPLE[ in_PeopleCount ];这是删除int数组的正确方法吗?
~c_House() { delete[] this->Array; };结构数组怎么样?
发布于 2013-03-23 04:58:18
正确的方法是使用std::string而不是char的动态数组,使用std::vector<PERSON>而不是PERSON的动态数组。
如果在类中动态地和手动地分配了数据,则必须确保遵循,即实现复制构造函数、赋值运算符和析构函数来执行数据的“深度复制”。这是为了确保类的每个实例都拥有其动态分配的数据,并确保复制和分配的安全性。在C++11中,这被推广到五的规则。
一个不相关的问题:包含前导下划线或任何位置的双下划线的名称都是为实现保留的。所以你不应该给你的变量命名,比如in__PeopleCount。
https://stackoverflow.com/questions/15579709
复制相似问题