Я пытаюсь выяснить реализацию очереди на основе массива в C++. На данный момент я просто пытаюсь инициализировать массив с размером, зависящим от того, что вводит пользователь. У меня есть класс Queue следующим образом:Указатель на массив не работает по назначению
Queue.h: #include
using namespace std;
class Queue {
private:
int *ptrtoArray;
int arraysize;
int data;
public:
Queue(int size);
Queue();
void print();
};
Queue.cpp:
#include "Queue.h"
Queue::Queue() {
}
Queue::Queue(int size) {
int theQueue[size];
arraysize = size;
ptrtoArray = &theQueue[0];
for (int i=0;i<size;i++) {
theQueue[i] = -1;
}
cout << "(";
for(int i=0;i<size;i++) {
cout << ptrtoArray[i] << ",";
}
cout << ")" << endl;
}
void Queue::print() {
cout << "(";
for(int i=0;i<arraysize;i++) {
cout << ptrtoArray[i] << ",";
}
cout << ")" << endl;
}
main.cpp:
#include <iostream>
#include "Queue.h"
using namespace std;
const string prompt = "queue> "; // store prompt
Queue *queue;
void options(){
string input; // store command entered by user
cout << prompt; // print prompt
cin >> input; // read in command entered by user
int queuesize,num;
while(input != "quit") { // repeat loop as long as user does not enter quit
if (input == "new") { // user entered ad
cin >> queuesize;
queue = new Queue(queuesize);
} else if (input == "enqueue"){ //user entered remove
} else if (input == "dequeue"){ //user entered remove
} else if (input == "print"){ //user entered quit
queue->print();
} else { // no valid command has been selected
cout << "Error! Enter add, remove, print or quit." << endl;
}
cout << prompt; // repeat prompt
cin >> input; // read new input
}
}//options
/**
* Main function of the program. Calls "options", which handles I/O.
*/
int main() {
options();
return 0;
}
Когда код выполняется, все в порядке с кодом внутри конструктора, но функция печати дает некоторую st результаты диапазона.
queue> new 5
(-1,-1,-1,-1,-1,)
queue> print
(134516760,134525184,-1081449960,4717630,134525184,)
queue>
Таким образом, на данный момент я просто хочу, чтобы функция печати(), чтобы показать мне, что массив содержит только -1 в каждом элементе. Мои знания указателей очень ограничены, поэтому, если вы могли бы помочь мне понять, что я делаю неправильно, это было бы здорово!
Это сработало, спасибо! Не могли бы вы объяснить, может быть, немного более подробно различие между двумя способами объявления этого? В частности, почему использование нового в этом случае имеет более широкий охват. – dmarzio
Я уверен. Я отредактирую ответ. – 2013-03-31 18:28:47
Благодарим вас за разъяснение. Я понимаю это сейчас. – dmarzio