【发布时间】:2020-12-16 22:02:25
【问题描述】:
我是 C++ 新手。我试图创建一个类似于multimap 的类,称为multimap_viewer。我希望能够将我的multimap_viewer 转换为multimap,但我只是不知道如何。我试图编写一个赋值运算符,但它不起作用。请有人指出我正确的方向吗?
演示错误的代码:
multimap_viewer<std::string, std::string> m_view;
std::map<std::string, std::string> mymap;
mymap[ "this" ] = "that";
m_view.add( mymap );
std::multimap<std::string, std::string, string_size_less> a = m_view;
我在最后一行收到的错误是:
没有合适的用户定义从“multimap_viewer<:string std::string>”到“std::multimap<:string std::string string_size_less std::allocator :pair>>>" 存在
我的想要工作分配操作员:
template <class T, class V>
class multimap_viewer
{
public:
std::multimap<T, V, class Comp, std::allocator<std::pair<const T, V>>>& operator=(multimap_viewer<T, V> mv)
{
std::multimap<T,V, class Comp, std::allocator<std::pair<const T, V>>> mp;
// copy items and stuff
return *mp;
}
}
【问题讨论】:
-
您不应该编写自定义赋值运算符,而应编写conversion function。