简体   繁体   English

我可以分配一个指针对象数组 = 另一个 object 吗?

[英]Can I assign an array of pointer objects = another object?

Say I have a building floor with a certain amount of rooms.假设我有一个有一定数量房间的建筑楼层。 Each room is empty.每个房间都是空的。 I want to give an empty room a type.我想给一个空房间一个类型。 I have an office type in mind that is already created and I want to give the first available empty room that office type.我有一个已经创建好的办公室类型,我想为第一个可用的空房间提供该办公室类型。

Room* availableRooms[max] {};
Office* mOffice = new Office;
// Values to mOffice are set later so it's not nullptr

for (int i = 0; int i < max; i++) 
{
    if (availableRooms[i] == nullptr) // If room is empty set it to the mOffice object
    {
        [i] = mOffice;
    }
}

Would this be the right way of doing it?这是正确的做法吗?

Assuming Office is a subtype of Room this should work, but you'd want to break after the assignment, otherwise all the empty rooms will point to mOffice , not just the first one:假设OfficeRoom的子类型,这应该可以工作,但是您希望在分配后break ,否则所有空房间都将指向mOffice ,而不仅仅是第一个:

for (int i = 0; int i < max; i++) {
    if (availableRooms[i] == nullptr) {
        availableRooms[i] = mOffice;
        break;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM