C++ 类成员在转换为模板后受到限制
所以我在使用模板时遇到了一个问题。在我将代码转换成模板后,我再也无法访问类的私有成员。我得到的错误是“current”是“Iterator”的私有成员。首先,我要上每节课:C++ 类成员在转换为模板后受到限制,c++,C++,所以我在使用模板时遇到了一个问题。在我将代码转换成模板后,我再也无法访问类的私有成员。我得到的错误是“current”是“Iterator”的私有成员。首先,我要上每节课: template <class T> struct nodeType { T info; nodeType<T> *link; }; template <class T> class Iterator { public: Iterator(); Itera
template <class T>
struct nodeType {
T info;
nodeType<T> *link;
};
template <class T>
class Iterator {
public:
Iterator();
Iterator(nodeType<T> *);
T operator*();
bool IsNull();
Iterator<T> operator++();
Iterator<T> operator++(int);
bool operator==(const Iterator<T> &) const;
bool operator!=(const Iterator<T> &) const;
Iterator<T> &operator=(T);
private:
nodeType<T> *current;
};
template <class T>
class LinkedList {
public:
LinkedList();
LinkedList(const LinkedList<T> &);
~LinkedList();
void InsertHead(T);
Iterator<T> InsertAfter(T, Iterator<T>);
Iterator<T> Search(T);
bool IsEmpty();
void Print();
void DestroyList();
Iterator<T> Start();
Iterator<T> End();
const LinkedList<T> &operator=(const LinkedList<T> &);
private:
nodeType<T> *head;
};
然后我尝试执行以下操作,但没有出现错误,但当我调用InsertAfter
函数向列表中添加新项时,它没有显示。我做了一个cout
newNode=input;它显示了我想要插入的值,但是节点没有;我似乎无法连接。为什么我不能使用以前的代码?比如newNode.current->link=findNode.current->link代码>
template <class T>
Iterator<T> Iterator<T>::operator++() {
current = current->link;
return *this;
}
template <class T>
Iterator<T> Iterator<T>::operator++(int) {
Iterator<T> temp;
temp = *this;
++(*this);
return temp;
}
template <class T>
Iterator<T> LinkedList<T>::InsertAfter(T input, Iterator<T> marker) {
Iterator<T> newNode = new nodeType<T>;
Iterator<T> findNode = marker;
newNode = input;
newNode++ = findNode++;
findNode++ = newNode;
return findNode;
}
模板
迭代器迭代器::运算符++(){
当前=当前->链接;
归还*这个;
}
模板
迭代器迭代器::运算符++(int){
迭代器温度;
温度=*此温度;
++(*本条);
返回温度;
}
模板
迭代器链接列表::InsertAfter(T输入,迭代器标记){
迭代器newNode=新节点类型;
迭代器findNode=标记;
newNode=输入;
newNode++=findNode++;
findNode++=newNode;
返回findNode;
}
您不能在LinkedList
的成员函数中执行newNode.current
,因为current
是迭代器的私有。这就是private
的意思-它只能从它所属类的成员函数中访问
很明显,你的“旧”代码是不同的。旧代码中可能有迭代器friend
LinkedList。如果你发布你的旧代码,它可能会把事情弄清楚。“在我使用模板之前”。你的模板代码在哪里?
template <class T>
Iterator<T> Iterator<T>::operator++() {
current = current->link;
return *this;
}
template <class T>
Iterator<T> Iterator<T>::operator++(int) {
Iterator<T> temp;
temp = *this;
++(*this);
return temp;
}
template <class T>
Iterator<T> LinkedList<T>::InsertAfter(T input, Iterator<T> marker) {
Iterator<T> newNode = new nodeType<T>;
Iterator<T> findNode = marker;
newNode = input;
newNode++ = findNode++;
findNode++ = newNode;
return findNode;
}