Clion c ++中有友元函数的错误

时间:2017-01-24 02:18:54

标签: c++ friend-function class-template

我编写了一个小代码来练习数据结构和漂亮的C ++。

如果将SNode中的变量设为公开并删除friend class ...行,则下面的代码完全正常。但是,根据我正在阅读的教科书,这应该可以正常工作。

我得到的错误如下:

  • line 11: error: ‘SLinkedList’ is not a class template
  • 在'class SNode'的实例化中:line 10: error: template argument required for ‘class SLinkedList’
  • 实例化'void SLinkedList :: addFront(const E&amp;)[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;
}

2 个答案:

答案 0 :(得分:1)

friend class SLinkedList<E>;

此模板尚未声明。从源文件的开头到结尾,您的C ++代码将以有序的方式进行编译。在此模板稍后在此头文件中声明之前,编译器不知道这是什么。

解决方案非常简单:在头文件的开头添加前向声明,因为SNode模板声明:

template <typename E> class SLinkedList;

template <typename E>
class SNode {
private:
    E elem;
    SNode<E> * next;
    friend class SLinkedList<E>;
};

答案 1 :(得分:1)

Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
    'numeric: digitValue contains the numeric value
    MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
    'non-numeric: digitValue contains an Integer's default value (0)
    MessageBox.Show("Not a number")
End If

此时friend class SLinkedList<E>; 尚未定义为模板,因此给出了错误。给SLinkedList一个前瞻性声明,一切都会好的。

添加: -

SLinkedList
相关问题