【发布时间】:2017-01-24 02:18:53
【问题描述】:
我编写了一个小代码来练习数据结构和漂亮的 C++。
如果将SNode 中的变量公开并删除friend class ... 行,则下面的代码完全可以正常工作。但是,根据我正在阅读的教科书,这应该可以正常工作。
我得到的错误如下:
line 11: error: ‘SLinkedList’ is not a class template- 在“类 SNode”的实例化中:
line 10: error: template argument required for ‘class SLinkedList’ - 在“void SLinkedList::addFront(const E&) [with E = int]”的实例化中:
line 9: error: ‘int SNode<int>::elem’ is private
下面是用Clion编写的代码:
#include <iostream>
using namespace std;
template <typename E>
class SNode {
private:
E elem; //line 9
SNode<E> * next; // line 10
friend class SLinkedList<E>; //Provide SLinkedList access to these private variables (line 11)
};
template <typename E>
class SLinkedList {
public:
SLinkedList();
~SLinkedList();
bool empty() const;
const E& front() const;
void addFront(const E& e);
void removeFront();
void printAll() const;
private:
SNode<E> * head;
};
template <typename E>
SLinkedList<E>::SLinkedList():head(NULL){};
template <typename E>
bool SLinkedList<E>::empty() const {
return (head==NULL);
}
template <typename E>
void SLinkedList<E>::addFront(const E &e) {
SNode<E> * node = new SNode<E>;
node->elem=e;
node->next=head;
head=node;
}
template <typename E>
void SLinkedList<E>::removeFront() {
SNode<E> * temp = head;
head = head->next;
delete temp;
}
template <typename E>
const E& SLinkedList<E>::front() const {
return head->elem;
}
template <typename E>
SLinkedList<E>::~SLinkedList() {
while (!empty()){
removeFront();
}
}
template <typename E>
void SLinkedList<E>::printAll() const {
SNode<E> * itr =head;
while (itr != NULL){
cout<<itr->elem<<" ";
itr = itr->next;
}
}
int main() {
cout << "Hello, World!" << endl;
SLinkedList<int> test ;
test.addFront(2);
test.addFront(3);
test.addFront(6);
test.addFront(8);
test.addFront(19);
test.printAll();
return 0;
}
【问题讨论】:
标签: c++ friend-function class-template