2015-11-03 60 views
0

你能告訴我,爲什麼我得到這個錯誤:常量和指針(節點例子)

source_file.cpp(41) : error C2664: 'void std::vector<Node<int> *,std::allocator<_Ty>>::push_back(Node<int> *const &)' 
        : cannot convert argument 1 from 'const Node<int> *' to 'Node<int> *&&' 

當我調用addChild方法?

這裏是我的類定義/實施:

template<class T> 
class Node 
{ 
    private: 
     T _value; 
     vector<Node*> children; 

    public: 
     Node(T value); 
     Node(const Node<T>& node); 
     void AddChild(const Node<T>* node); 
     T getValue() const; 
     vector<Node<T>*> returnChildren() const; 
     ~Node(); 
}; 

template <class T> 
Node<T>::Node(T value):_value(value) 
{ 
} 

template <class T> 
Node<T>::Node(const Node& node):_value(node.getValue()), 
           children(node.returnChildren()) 
{ 
} 

template <class T> 
void Node<T>::AddChild(const Node* node) 
{ 
    children.push_back(node); 
} 

template <class T> 
T Node<T>::getValue() const 
{ 
    return _value; 
} 

template <class T> 
vector<Node<T>*> Node<T>::returnChildren() const 
{ 
    return children; 
} 

template <class T> 
Node<T>::~Node() 
{ 
    for (vector<Node*>::iterator it=children.begin() ; it!=children.end() ; it++) 
    { 
     delete (*it); 
    } 
} 
+1

'vector children;'需要一個非'const'指針。改變函數的簽名:'void AddChild(Node * node);'。 –

+1

由於'X * const&'與'const X *'不同,'const'關鍵字不會在兩個聲明中指向同一個東西。 – Holt

回答

0

children包含指針到非const。
node參數是一個指向const的指針。

這些類型不兼容。

要麼將​​指針指向常量存儲在children中,要麼將node參數指向非常量指針。