0

在类中声明动态结构和无符号字符数组的正确方法是什么?

#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; };

结构数组呢?

4

1 回答 1

2

正确的做法是用std::string代替动态数组,用动态char数组std::vector<PERSON>代替PERSON.

如果你在一个类中有动态和手动分配的数据,你必须确保你遵循三个规则,即实现一个复制构造函数、赋值操作符和析构函数来执行数据的“深度复制”。这是为了确保您的类的每个实例都拥有其动态分配的数据,并使复制和分配安全。在 C++11 中,这被推广到五规则

一个不相关的问题:包含前导下划线或任何位置的双下划线的名称保留用于实现。所以你不应该给你的变量名称,例如in__PeopleCount.

于 2013-03-22T20:58:18.003 回答