在Map中使用Node,C ++

问题描述 投票:0回答:2
class MtmMap {   
    public:    
    class Pair {     
         public:   
         Pair(const KeyType& key, const ValueType& value) :     
             first(key),       
             second(value) { }    
         const KeyType first;    
         ValueType second;    
     };     
    class node {    
        friend class MtmMap;    
        Pair data;    
        node* next;     
        public:    
        node();    
        node(const Pair& pair){
            data.Pair(pair.first , pair.second);
            next = NULL;
        }    
    };
    node* temp = new node(pair);
}

错误:

调用'mtm :: MtmMap <int,int,AbsCompare> :: Pair :: Pair()'没有匹配函数 无效使用'mtm :: MtmMap <int,int> :: Pair :: Pair' 'void mtm :: MtmMap :: insert(const。) mtm :: MtmMap <KeyType,ValueType,CompareFunction> :: Pair&)[与KeyType = int; ValueType = int; CompareFunction = AbsCompare]'

c++ class nodes public std-pair
2个回答
0
投票

通过为Pair定义一个带有参数的构造函数,可以删除不带参数的隐式默认构造函数。如果你在Pair中有node类型的成员,那么它必须在节点的初始化列表中传递给它的参数,你需要用这个替换你的节点构造函数:

    node(const Pair& pair) : data(pair.first, pair.second) {
        next = NULL;
    }

这将正确调用data上的构造函数。 Learn Cpp有一个关于初始化列表如何工作的教程,您可能想要阅读。


0
投票

跳出来的第一件事是这一行:

node* temp = new node(pair);

看起来你正试图在类定义中使用new类。这可能是问题的一部分。此外,这个区域看起来有点困惑:

node(const Pair& pair){
  data.Pair(pair.first , pair.second);
  next = NULL;
}

看起来你正试图直接调用Pair构造函数。我不确定这是否是有效的C ++。真的,只需为Pair定义一个拷贝构造函数,如下所示:

Pair( Pair const& other )
  : first( other.first )
  , second( other.second )
{}

然后,该块变为

node( Pair const& pair )
  : data( pair )
  , next( NULL )
{}

您也可以查看std::pair

© www.soinside.com 2019 - 2024. All rights reserved.