0

クラス内で動的構造体と unsigned char 配列を宣言する適切な方法は何ですか?

#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ことです。charstd::vector<PERSON>PERSON

クラスにデータを動的かつ手動で割り当てた場合は、必ず3 つのルールに従う必要があります。つまり、コピー コンストラクタ、代入演算子、およびデストラクタを実装して、データの「ディープ コピー」を実行します。これは、クラスの各インスタンスが動的に割り当てられたデータを所有し、コピーと割り当てを安全にするためです。C++11 では、これは5 の規則に一般化されます。

無関係な問題: 先頭のアンダースコアまたは二重アンダースコアを含む名前は、実装用に予約されています。したがって、変数に などの名前を付けないでくださいin__PeopleCount

于 2013-03-22T20:58:18.003 に答える