尝试在映射C++中存储指向抽象类的指针

Trying to store a pointer to an abstract class in a map C++

本文关键字:抽象类 指针 存储 映射 C++      更新时间:2023-10-16

我有一个程序,它将指向抽象类的指针存储到map中,以便我可以使用map中的数据来调用抽象类的具体类(使用工厂方法)。

它需要存储一个指针,因为类是抽象的,但问题是当我做一个指针时,我得到错误

没有匹配的成员函数来调用"insert"

我的代码如下所示:

形状工厂类标头

#ifndef ShapeFactoryManager_hpp
#define ShapeFactoryManager_hpp
#include <stdio.h>
#include "ShapeFactory.h"
#include "CircleFactory.h"
#include "PolygonFactory.h"
#include "LineFactory.h"
#include <map>
class ShapeFactoryManager
{
public:
    ShapeFactoryManager();
    const static ShapeFactoryManager& getInstance();
    ShapeFactory createFactory(unsigned long shapeID) const;
    bool RegisterShape(unsigned long id, ShapeFactory* factory) const;
private:
    const std::map<unsigned long, ShapeFactory*>registrationTable;
};
#endif /* ShapeFactoryManager_hpp */

形状工厂经理.cpp

bool ShapeFactoryManager::RegisterShape(unsigned long id, ShapeFactory* factory) const
{
    registrationTable.insert(std::make_pair(id, factory));
    return true;
}

错误发生在:

registrationTable.insert(std::make_pair(id, factory)); 

std::map::insert 是一个不是 const 成员函数。从逻辑上讲,这是非常合乎逻辑的,因为如果地图是恒定的,我们就无法添加或删除它。

删除 registrationTableRegisterShape 的常量限定符。如果成员函数需要更改状态,它也不应该是常量。