我有一个程序将指向抽象类的指针存储到映射中,这样我就可以使用映射中的数据来调用抽象类的具体类(使用工厂方法)。
它需要存储一个指针,因为类是抽象的,但问题是当我 make 是一个指针时,我得到了错误
No matching member function to call '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 成员函数。从逻辑上讲是这样,因为如果映射是常量,我们就不能向其中添加或从中删除。
删除 registrationTable
和 RegisterShape
的 const 限定符。如果一个成员函数需要改变状态,它也不应该是 const。
关于c++ - 试图在映射 C++ 中存储指向抽象类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47195141/