Access array in header file C++

Rob*_*son 1 c++ class constants member-functions pass-by-reference

I have an object Room and each Room has an array of 4 references to other rooms

header file:

namespace test
{
    class Room
    {
    public:
        Room* references[4];
        void Connect(Room roomReference) const;
    }
}
Run Code Online (Sandbox Code Playgroud)

and in my cpp file, I am attempting to attach that reference by inserting the pointer of the room to a specific index in references. However, I get the following compiler error "Cannot assign to readonly type Room* const." But when I create a local variable of the same type and insert into there, it works.

void Room::Connect(Room roomReference) const
{
    Room* roomReferenceItem = &roomReference;
    Room* foos[4];
    // This works
    foos[2] = roomReferenceItem;

    // This does not
    this->references[2] = roomReferenceItem;
}
Run Code Online (Sandbox Code Playgroud)

I am not sure if there is some misunderstanding I am having with global arrays in C++

Vla*_*cow 5

您声明了一个常量成员函数

void Connect(Room roomReference) const;
Run Code Online (Sandbox Code Playgroud)

因此,您不能更改类的数据成员,因为在这种情况下,指针的this定义类似于const Room *.

const从函数声明中删除限定符。

此外,您还必须通过引用函数来传递该类型的对象,Room例如

void Connect(Room &roomReference);
Run Code Online (Sandbox Code Playgroud)

否则,存储在数组中的指针references将无效,因为它们在退出函数后将指向非活动的临时对象。