I am currently trying to write my first template class as an assignment for my c++ class, but I don't understand why I keep getting this error:
g++ -c main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:12:14: error: cannot convert ‘Dequeu<int>’ to ‘int’ in initialization
int ou = i[0];
main.cpp:
#include "main.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main (int args, char ** argc){
Dequeu<int>* i = new Dequeu<int>();
i->push_back (10);
int ou = i[0];
cout<<"i[0]: "<<ou<<endl;
}
with main.h:
#include "Dequeu.h"
dequeu.h:
#ifndef MAIN_H
#define MAIN_H
#endif
#include "Node.h"
#include <stddef.h> //NULL
template<typename T>
class Dequeu {
public:
Dequeu(); ~Dequeu();
void push_back(T);
T &operator[] (int i) {
if (i<size && i>=0){
//head?
if (i == 0)
return head->value;
//tail?
if (i == size-1)
return tail->value;
//other:
Node<T>* temp = head;
i--;
while (i != 0 ){
temp = temp->next;
i--;
}
return temp->Value();
}
}
private:
Node<T> * head;
Node<T> * tail;
int size;
};
template<typename T>
Dequeu<T>::Dequeu() {
head->nullify();
tail->nullify();
}
template<typename T>
Dequeu<T>::~Dequeu(){
Node<T>* temp = head;
while (temp->Next() != NULL) {
temp = temp->next;
delete(head);
head=temp;
}
}
template<typename T>
void Dequeu<T>::push_back(T t){
Node<T>* newNode;
newNode->Value(t);
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
if (head == NULL)
head = tail;
size++;
}
and Node.h:
#include <stddef.h> //NULL
template <typename T>
class Node {
public:
Node<T>* prev;
Node<T>* next;
T value;
Node(); ~Node();
void nullify ();
private:
};
template <typename T>
void Node<T>::nullify() {
this->value = NULL;
this->next = NULL;
this->prev = NULL;}
The last thing I tried was event just returning this->head->value
without checking the input integer in operator[].
The class is not finished yet, so don't wonder why there are only two functions implemented...
Please feel free to tell me how to write this code better if you find something very bad in it, I am really bad in this.