我无法理解为什么我在Node ctor上收到转换错误,节点构造函数接受' const T&'作为第一个参数,这就是我的插入方法传递给构造函数但由于某种原因它仍然抛出我的错误。
错误C2440:'初始化' :无法转换为&#const;记录'到' SortedList<> :: Node *
SortedList的类型为'记录'但如果我在中间键入任何内容<>括号之间的所有内容都将消失。
列表类:
class SortedList{
struct Node{
T data_;
Node* next_;
Node* prev_;
Node(const T& data=T{},Node* nx=nullptr,Node* pr=nullptr){
data_ = data;
next_ = nx;
prev_ = pr;
}
};
Node* front_;
Node* back_;
public:
class const_iterator{
friend class SortedList;
protected:
Node* curr_;
const_iterator(Node* n){
curr_ = n;
}
public:
const_iterator(){
curr_ = nullptr;
}
const_iterator operator++(){
curr_ = curr_->next_;
return *this;
}
const_iterator operator++(int){ //advances curr returns old
const_iterator old = *this;
curr_ = curr_->next_;
return old;
}
const_iterator operator--(){
curr_ = curr_->prev_;
return *this;
}
const_iterator operator--(int){
const_iterator temp = *this;
curr_ = curr_->prev_;
return temp;
}
bool operator==(const_iterator rhs){
return curr_->data_ == rhs.curr_->data_;
}
bool operator!=(const_iterator rhs){
return curr_->data_ != rhs.curr_->data_;
}
bool operator<(const_iterator rhs){
return curr_->data_ < rhs.curr_->data_;
}
const T& operator*()const{
return curr_->data_;
}
};
正在抛出转换错误:
template <typename T>
typename SortedList<T>::iterator SortedList<T>::insert(const T& data){
Node* n(data);
iterator it_temp(n);
iterator sort(front_);
while (sort < it_temp){
++sort;
}
n.next_ = sort.curr_;
n.prev_ = sort.curr_->prev_;
sort.curr_->prev_->next_ = n;
sort.curr_->prev_ = n;
}
该错误特别是在插入函数中构造Node * n的情况下抛出。
答案 0 :(得分:1)
你不能构造像这样的指针
Node* n(data);
例如,您必须使用new
Node* n = new Node(data);