2017-10-12 2 views
0

이 코드는 문제가 있습니다. 내가 클래스의 두 함수를 호출 할 때마다 그리고 그 클래스에서 if-else 문이 있고 화면에 출력을 출력 할 때마다 else 함수가 아니라 두 함수의 if 절만 실행하게됩니다. 이 문제를 어떻게 해결할 수 있습니까? 예를 들어루프에서 두 개의 큐 클래스 함수 호출

: 이 내 Queue.h 파일입니다

#ifndef QUEUE_H 
#define QUEUE_H 

class Queue { 
private: 
    //private variables 
    int arr_size; 
    char *arr; 
    int head; 
    int tail; 
    int count; 
public: 
    Queue(int); //constructor 
      //functions 
    int enqueue(char); 
    int dequeue(char&); 
}; 
#endif 

이 내 Queue.cpp 파일입니다

#include <iostream> 
#include "Queue.h" 
using namespace std; 
Queue::Queue(int size) { 
    //initializing 
    arr_size = size; 
    arr = new char[size]; 
    for (int i = 0; i < arr_size; i++) { 
     arr[i] = NULL; 
    } 
    head = 0; 
    tail = 0; 
    count = 0; 
} 
int Queue::enqueue(char value) { 
    if (count<arr_size) //if array is not full, execute below 
    { 
     arr[tail++] = value; //pass value of first-to-last element in array 
     count++; //counting the input value 
     cout << "\nEnqueue Value: "<< arr[tail-1]; 
     return 0; 
    } 
    else { 
     tail = 0; 
     cout << "\nArray is full. Value cannot be write: " << value; 
     return -1; 
    } 
} 
int Queue::dequeue(char &read_val) { 
    if (count !=0) { //if array has elements, execute below 
     read_val = arr[head]; //pass-by-reference the value of first-to-last element in array to parameter of function 
     cout <<"\nDequeue Value: "<<read_val; 
     arr[head] = NULL; 
     count--; 
     if (head++ == arr_size) { 
      head = 0; 
     } 
     return 0; 
    } 
    else if (count ==0) { 
     cout << "\nArray is empty. Cannot be dequeue"; 
     return -1; 
    } 
} 

그리고 이것은 무엇을 내 소스 파일입니다

#include "Queue.h" 
#include <iostream> 
using namespace std; 
int main() { 
    int n; 
    cout << "Please enter the desired size of the array: "; 
    cin >> n; 
    char read_val = NULL; 
    Queue myqueue(n); 
    char arr[] = "Hello World, this is ELEC3150"; 
    int size = sizeof(arr)-1; 
    int count = 0; 
    for (int i = 0; i < 5; i++) { 
     myqueue.enqueue(arr[count]); 
     count++; 
     myqueue.dequeue(read_val); 
    } 

배열의 크기를 5보다 작게 입력하면 arra를 나타내는 오류 메시지가 인쇄되어야합니다 y는 enqueue 함수에서 꽉 차고 배열은 dequeue 함수에서 비어 있지만 그렇지 않습니다.

+0

Eric Lippert의 [작은 프로그램 디버깅 방법] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 읽어보십시오. –

+0

왜'main'이이 변수'count'를 가지고 있습니까? 왜 그냥'myqueue.enqueue (arr [i]); '를 사용하지 말고 –

+0

... 그리고 마지막으로 queue.h를 보여줘. –

답변

0

이제는 알았습니다. 5 문자를 큐에 넣고 5 문자를 큐에 넣으려고했기 때문에. 내 메인에 배열 arr의 끝까지 반복합니다. 그래서 dequeue와 enqueue를 2 개의 for 루프로 분리하면 while 루프에서 여전히 존재합니다.