Добавить объект на карту в конструктореC++

Программы на C++. Форум разработчиков
Ответить
Гость
 Добавить объект на карту в конструкторе

Сообщение Гость »


I would like to have objects add a pointer pointing to themselves into a map which is a member of another class.
Here is what I have so far:

Код: Выделить всё

// entitymanager.h
// Inside the public part of the EntityManager class
std::map  AllMapEntities;

// main.cpp
EntityManager.AllMapEntities.insert({ 1, pObject1});

// mapentity.cpp
// constructor for MapEntity
MapEntity::MapEntity(){
EntityManager.AllMapEntities.insert({ meid, this });
}
It compiles and I can interact with the map and the object pointer is in there. the object is something that exists already before it is added to the map.
However if I try to have the object add the pointer during its construction then it fails.
The errors in

Код: Выделить всё

mapentity.cpp
are at the dot and at the first curly bracket and the errors are "expected an identifier" and "expected a type specifier".
I don't see why the same syntax would work if called in

Код: Выделить всё

main.cpp
however it would not work in the constructor.
Here is a minimal example in one main file.
It won't compile on that site because it requires SDL.
However the errors are the same as in the previous code pieces.

Код: Выделить всё

#include 
#include 
#include 
#include 
#include 
#include 

class EntityManager {
private:
public:

std::map  AllMapEntities;
EntityManager();
void CreateMapEntity();
};

class MapEntity {
private:
public:

// Constructor
MapEntity();
};

MapEntity::MapEntity() {
// This is the line with the 2 errors:
EntityManager.AllMapEntities.insert({ meid, this });
}

int main(int argc, char* argv[]) {

return 0;
}
The errors are both C2059 syntax errors.


Источник: https://stackoverflow.com/questions/781 ... onstructor
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»