2017-10-12 12 views
0

私はこのコードで問題があります。私はクラスの2つの関数を呼び出すと、それらのクラスでは、if-elseステートメントがあり、画面上に出力を印刷すると、else関数ではなく、2つの関数のif節のみが実行されます。どうすればこの問題を解決できますか?例えばループ内で2つのキュークラス関数を呼び出す

: これは私の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がいっぱいで、配列はデキュー機能では空ですが、デキュー機能では空です。

+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文字をデキューしました。私のメインの配列arの終わりまで繰り返します。したがって、デキューとエンキューを2つのforループに分けると、whileループではまだ存在します。

関連する問題