2017-04-05 4 views
0

저는 대학에서 C++ 첫 해에 있습니다. 그리고 내 교수는 한 달 안에 최종 테스트를위한 몇 가지 리뷰를 할당했습니다. 나는 내 지식으로, 다른 모든 질문을했다. 그러나이 두 가지 질문은 조금 이상하다. 본질적으로 교수님은 ListA이라는 클래스를 만들었습니다.이 클래스는 동적으로 할당 된 배열을 기본 저장소 구조로 사용합니다.클래스에서 동적으로 할당 된 배열 사용하기 스토리지 구조

  • 밖으로 쓰기에 필요한 private 변수
  • 내가 쓴 생성자를 들어 클래스 ListA

의 생성자 쓰기 : 아래의 코드 감안할 때, 그는 두 가지 작업을 수행하기를 원하십니다 :

List::List(int size) 
    { 
     array = new ItemType[size]; 
     length = 0; 
     head = array[0]; 
    } 

필요한 개인 변수에 대해 wro te :

itemType* array; 
    int length; //to keep track how many elements are filled 
    itemType* head; //to create pointer for first element in array 
    itemType size; 

이 줄이 맞는지 확실하지 않습니다. 나는 가까이있는 것처럼 느껴지지만 도움이 필요합니다. .h 파일은 다음과 같습니다.

typedef int itemType; 
class ListA 
{ 
public: 
List(int size); 
~List(); 
/* 
pre: an instance of lists exists 
post: true if list is empty, false otherwise 
*/ 
bool IsEmpty(); 
/* 
pre: an instance of list exists 
post: returns len 
gth of the list 
*/ 
int GetLength(); 
/* 
pre: an instance of list exists 
post: newItem is at the head of the list 
*/ 
void PutItemH(itemType newItem); 
/* 
pre: an instance of list exists and is not empty 
post: Returns the contents of the head of the list. 
*/ 
itemType GetItemH(); 
/* 
pre: an instance of list exists and is not empty 
post: head of the list is deleted 
*/ 
void DeleteItemH(); 
/* 
pre: an instance of list exists an 
d is not empty 
post: contents of list nodes are displayed on subsequent lines from head to tail 
*/ 
void Print(); 
/* 
Pre: an instance of list exists 
Post: returns true if the target is in the list, false otherwise 
/* 
bool Find(itemType 
target) 
/* 
Pre: an instance of list exists 
Post: if a node contains target, the node is deleted and true is returned, else false is returned. 
/*bool DeleteItem (itemType target) 
private: 
#notice that there are no member variables 
. See problem 14. 
}; 
+1

그럼 정확히 무엇이 문제입니까? 무엇이 작동하지 않습니까? btw,'head'는 순환 배열과 같은 것을하지 않는 한'array'가 이미 머리를 가리키고 있기 때문에 불필요한 것처럼 보입니다. –

+0

일반적으로리스트를 호출하면리스트가되지 않습니다. 데이터 형은 그것의 행위, 메소드의 의미론에 의해 효과적으로 정의된다. 한 지점에서만 요소를 추가하고 제거 할 수있는 컨테이너를 일반적으로 _stack_이라고합니다. 귀하의 예제에서, 주석 처리 된'DeleteItem' 메소드 만이 스택 컨테이너의 메소드와 다릅니다. – MSalters

답변

0

많은 멤버 변수가 필요하지 않습니다.

itemType* array; 
int length; //to keep track how many elements are filled 
itemType* head; //to create pointer for first element in array - Why ? 
itemType size; 

이 다음과 같아야합니다

itemType* array; 
int length; 
int size; 

생성자에 아래로 트림 할 수 있습니다 : 이것은 모든 구성원 functions.Eg의 요구를 충족하기에 충분합니다

List::List(int size):size(size), length(0) 
{ 
    array = new ItemType[size]; 
} 

:

bool ListA::IsEmpty() {return length == 0;} 
int ListA::GetLength() {return length;} 

length은 기본 배열에 항목을 추가 할 때 증가합니다.

+0

틀린 - 목록 메서드가 머리를 변경할 수 있도록하려면 머리가 필요합니다. (pust_front/pop_front 메소드가 떠오른다). 사실, 목록 노드가 독립적으로 할당 해제되므로 사용법을 아는 것은 불충분하며 노드가 무엇인지 정확히 알아야합니다. – MSalters