Прежде всего, я понимаю, что в C++ уже существует класс для динамического массива. Я делаю это из экспериментов, а не из-за необходимости. У меня есть класс DynamicCharArray. Мое намерение состоит в том, чтобы реализовать динамический массив, используя связанный список. Он содержит несколько методов, некоторые частные и некоторые публичные. Два из них:
void InterInsert(node *&head, node *&last, int index, char input)
а также
void insert(int index, char input).
InterInsert (...) содержит весь код для фактического вставки символа в мой массив. insert (...) является абстракцией.
Мои вопросы: я на правильном пути, а если нет, как мне это реализовать? Почему я получаю следующие ошибки?:
error: ожидаемое первичное выражение перед токеном '*' this → InterInsert (node * & head, node * & last, int index, char input);
error: "head" в этой области не объявлялся → InterInsert (node * & head, node * & last, int index, char input);
error: ожидаемое первичное выражение перед токеном '*' this → InterInsert (node * & head, node * & last, int index, char input);
error: "last" не был объявлен в этой области: - InterInsert (node * & head, node * & last, int index, char input); error: ожидаемое первичное выражение перед 'int' this → InterInsert (node * & head, node * & last, int index, char input);
error: ожидаемое первичное выражение перед "char" this → InterInsert (node * & head, node * & last, int index, char input);
Эта программа все еще находится на ранних стадиях. Но я бы очень хотел исправить эти ошибки, прежде чем продолжить. В будущем может быть добавлено много методов, и предложения по этому вопросу будут очень признательны.
в DynamicCharArray.h:
#ifndef DYNAMICCHARARRAY_H
#define DYNAMICCHARARRAY_H
class DynamicCharArray
{
private:
struct node
{
char let;
node *next;
int index;
};
int size;
bool isEmpty(node *head);
void InterInsert(node *&head, node *&last, int index, char input);
void insertAsFirstElement(node *&head, node *&last, char input);
public:
DynamicCharArray(); //create empty array
void insert(int index, char input); //insert an element into array
void printAll(); //print all data values contained in the array
char index(int numIn); //returns the char value in a particular index. Same effect as: myArray[numIn] instead I will call it as: myChar = myDynamicCharArray.index(5)
~DynamicCharArray();
};
#endif // DYNAMICCHARARRAY_H
в DynamicCharArray.cpp:
#include "dynamicchararray.h"
#define NULL 0
struct node
{
char let;
node *next;
int index;
};
int size;
DynamicCharArray::DynamicCharArray() //create empty array
{
node *head = NULL;
node *last;
node list;
size = 0;
}
bool DynamicCharArray::isEmpty(node *head)
{
if(head == NULL)
{
return true;
}
else
{
return false;
}
}
void DynamicCharArray::InterInsert(node *&head, node *&last, int index, char input)
{
if(isEmpty(head))
{
insertAsFirstElement(head, last, input);
}
else
{
node *newNode = new node; //new node is dynamicly created (space created)
newNode -> let = input; //value that is passed is assigned to new node
newNode -> next = last -> next; //the new node pointer gets the same value as the last pointer, as it is now in the 'place' where last was.
last -> next = newNode; //The new node is now the last, and the last node now points to it
last = last -> next; //make last, point to the last element in the list
}
}
void DynamicCharArray::insertAsFirstElement(node *&head, node *&last, char input) //insert as first element function from standard linked list program
{
node *newNode = new node;
newNode -> index = 0;
newNode -> let = input;
newNode -> next = NULL; //Here is the difference between the first element, and the rest. Here the tail/last pointer to node does not have a value yet. It will get this node value in the rest of this function.
head = newNode;
last = newNode;
}
void DynamicCharArray::insert(int index,char input) //insert an element into array
{
InterInsert(node *&head, node *&last, int index, char input); //HERE IS THE LINE THE ERRORS ARE REFERING TO
}
char DynamicCharArray::index(int numIn) //returns the char value in a particular index. Same effect as: myArray[numIn] instead I will call it as: myChar = myDynamicCharArray.index(5)
{
}
DynamicCharArray::~DynamicCharArray()
{
}
в main.cpp:
, ,
DynamicCharArray myDynamicCharArray1 = DynamicCharArray();
myDynamicCharArray1.insert(0,'a');
, ,
Спасибо за чтение!
Чтобы просто ответить на ваш вопрос, это происходит из-за синтаксической ошибки, когда вы вызываете функцию InterInsert:
void DynamicCharArray::insert(int index,char input) //insert an element into array
{
InterInsert(node *&head, node *&last, int index, char input);
}
В этом случае у вас есть определение прототипа внутри функции, что является незаконным. Чтобы выполнить вызов функции, выполните следующее:
void DynamicCharArray::insert(int index, char input) //insert an element into array
{
node* head = new node; // you should probably edit these...
node* last = new node;
InterInsert(head, last, index, input);
}