我正在尝试创建一个队列,这需要创建存储在队列中的另一个对象。错误是
binary.cpp: In function ‘int main()’:
binary.cpp:183:1: error: ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’ is private
Queue<T>::Queue(T item){
^
binary.cpp:286:65: error: within this context
Queue<binary<string>*>* queue = new Queue<binary<string>*>(tree);
^
和
binary.cpp: In instantiation of ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’:
binary.cpp:286:65: required from here
binary.cpp:132:1: error: ‘Link<T>::Link(T) [with T = binary<std::basic_string<char> >*]’ is private
Link<T>::Link(T item){
^
binary.cpp:184:7: error: within this context
head = new Link<T>(item);
第一个是队列的实例化,第二个来自队列的构造函数,它在第一个错误的实例化行中调用。重要的声明和定义是:
template<class T>
class Link{
Link(T item);
private:
T content;
Link<T>* next;
};
template<class T>
Link<T>::Link(T item){
content = item;
next = NULL;
}
template<class T>
class Queue{
Queue();
Queue(T item);
private:
Link<T>* head;
Link<T>* end;
int length;
};
template<class T>
Queue<T>::Queue(T item){
head = new Link<T>(item);
end = head;
length = 1;
}
Link 类在 Queue 类之前声明和定义,两者在代码中使用之前声明和定义。谢谢你的时间。
默认情况下类成员是私有的,即使您稍后使用private
访问说明符, 你的代码是这样的:
template<class T>
class Queue{
Queue(); //Implicitly private
Queue(T item); //Implicitly private
private: //explicit private
Link<T>* head;
Link<T>* end;
int length;
};
所以你需要公开构造函数:
template<class T>
class Queue{
public:
Queue();
Queue(T item);
private:
Link<T>* head;
Link<T>* end;
int length;
};
Link<T>
类模板也是如此。