2016-07-14 3 views
0

소멸자가 아래 코드에서 호출하는 방법에 대한 빠른 질문이 있습니다. 난 ~LinkedList() 정의를 호출하는 소멸자 clear() 동적 메모리를 해제하는 기능이 있습니다.LinkedList 내용 삭제 (소멸자)

따라서 LinkedList ll_one을 삭제하려면 어떻게해야합니까 (아래의 source.cpp에서)? 아래 출력 비슷해 : 링크리스트를 출력하기

...

연결 목록 일 {19, 18, 17, 16, 15}

소멸자 링크리스트를 출력하기

라고 하나 ...

링크 된 목록의 하나 {}


//Source.cpp 
#include <iostream> 
#include "LinkedList.h" 
using namespace std; 

int main() { 
    LinkedList ll_one("Linked List one"); 
    int num = 0; 
    for (unsigned int i = 15; i < 20; ++i) { 
     ll_one.insertFront(i); 
    } 
    cout << "Outputting Linked List one..." << endl; 
    cout << ll_one << endl; 

    // How to delete the ll_one? 
    cout << "Outputting Linked List one..." << endl; 
    cout << ll_one << endl; 

    system("pause"); 
} 
+0

'll_one.clear(); – Drop

+0

소멸자는 또한'}'맨 마지막 (범위의 끝 부분)에서 호출되는' – Drop

+0

주어진 당신에 코드에서'll_one'은 자동적으로 소멸자를 가질 것입니다. 소멸자가 옳은 일을하는 한, 당신은 끝났습니다. 명시 적으로 삭제할 필요가 없습니다. 그것이 소멸자의 목적입니다. – GManNickG

답변

0

ll_one



//LinkedList.h 
#ifndef LINKEDLIST 
#define LINKEDLIST 
#include <ostream> 
#include "Node.h" 

class LinkedList { 
    Node* head; 
    Node* tail; 
    std::string name; 

    void recursePrint(Node*, std::ostream&) const; 

public: 
    LinkedList(); 
    LinkedList(std::string); 
    // destrcutor declaration 
    ~LinkedList(); 
    void setName(std::string); 
    std::string getName() const; 

    void insertFront(int); 
    void insertBack(int); 
    void clear(); 
    void print() const; 
    void print(std::ostream&) const; 
    void printReverse() const; 
    void printReverse(std::ostream&) const; 

    friend std::ostream& operator<<(std::ostream&, const LinkedList&); 

}; 
#endif /*LINKEDLIST*/ 
//Node.h 
#ifndef NODE 
#define NODE 
struct Node { 
    int value; 
    Node* next; 

    Node(int i) : value(i), next(nullptr) {} 
    Node() : value(0), next(nullptr) {} 
}; 
#endif /*NODE*/ 
이 스택에 생성된다. 그 객체가 main의 범위를 벗어나면 자동으로 꺼내지며 소멸자가 호출됩니다. 힙에 할당 한 경우 수동으로 delete를 호출하면됩니다.

다음은 힙에 할당되는 예제입니다.

LinkedList* ll_one = new LinkedList(); 
delete ll_one; 

목록을 비우거나 삭제하기 전에 사용중인 공간을 비우려면 지우기를 호출하십시오.

LinkedList* ll_one = new LinkedList(); 
ll_one->clear(); 
delete ll_one; 

스택

LinkedList ll_one; 
ll_one.clear(); 
+0

답변 해 주셔서 감사합니다. 하지만 그것이 범위를 벗어나기 전에 소멸자로부터 cout을 표시하는 방법이 메인의 범위에 있다면 궁금합니다. 현재 구조를 변경하지 않고이 작업을 수행 할 수 있는지 여부를 확인하려고합니다. – OpenMaze