2014-09-23 2 views
0

Привет всем Я работаю с моим списком массива и использовал его на некоторое время, и теперь я просто попытался использовать тип структуры в моем списке массива в этой программе:ArrayList Невозможно вернуть STRUCT

#include "stdio.h" 
#include "Header.h" 

int main(int argc, char**argv) 
{ 
    struct Params 
    { 
     int i; 
     int j; 


    }; 
    Params p2; 
    p2.i = 2; 
    p2.j = 3; 
    List::ArrayList<Params> p = List::ArrayList<Params>(); 
    p.add(p2); 
    printf("i: %d, j: %d", p.get(0).i, p.get(0).j); 

    return 0; 
} 

и это моя ArrayList программа:

#ifndef ARRAYLIST_H_ 
#define ARRAYLIST_H_ 
#include <iostream> 
using namespace std; 
namespace List 
{ 

    template <class T>//template - allows the user to choose what type to store in the list 
    class ArrayList 
    { 
    private://private variables 
     int length = 1;//sets the length to 1 
     T *a1 = (T*)calloc(length, sizeof(T));//allocates enough memory for 1 item 

    public://public functions 
     ArrayList() 
     {//constructor 
      //does nothing but you probably already knew that 

     } 
     ~ArrayList(){//destructor 
      //frees up the memory that a1 is pointing to 
      free(a1); 
     } 
     inline void add(T item){//adds an item to the list 

      if (length != 0) 
      {//if length is not equal to 0 


       a1 = (T*)realloc(a1, length*sizeof(T));//re-allocates memory 

       a1[length - 1] = item;//adds item to the end of the list 
       length++;//adds 1 to the length 
      } 
      else 
      {//else if it is equal to 0 


       a1[length] = item;//adds item to the front of the list 


      } 
     } 
     inline void remove(T item){ 

      if (length != 0) 
      { 
       length--;//subtracts 1 from the length 
       T *b = (T*)calloc(length, sizeof(T));//creates a new pointer to a memory block of size length 
       int idxModifier = 0;//modifies the index so it adds the items to the array in the right places 
       int i = 0;//counter/index 
       while (i < length){ 
        if (a1[i] != item)//if the item at the index of i is not equal to item we want to delete 
        { 
         b[i] = a1[i + idxModifier]; 

        } 
        else 
        { 
         idxModifier++;//adds 1 to the index modifier 
         b[i] = a1[i + 1];//adds the next item so we dont add the item back to the array 


        } 

        i++;//adds one to i 
       } 

       if (count != 0) 
        a1 = (T*)realloc(b, length*sizeof(T)); 
       else 
        cout << "The item does not exist!" << endl;//lets the user know that item does not exist 

       free(b);//frees up the memory that b allocated at the top of the function 
      } 
      else 
      { 
       cout << "You cannot delete anything because there is nothing in the list" << endl;//lets the user know that there is nothing in the list 
      } 

     } 
     inline T get(int i){//gets the integer at the index of i 


      return length != 0 ? a1[i] : NULL;//returns a[i] if the length is not 0, if it is 0 then it returns NULL wich is defined as 0 
     } 
     inline void set(int i, T type) 
     { 
      a1[i] = type;//sets whatever is at teh index of i to type 
     } 
     inline int size(){//gets the size 

      return length != 0 ? length - 1 : NULL;//if the length is not equal to 0 then it returns the length-1 , if it is not 0 then it returns NULL 
     } 
     inline void print(){//prints the list 
      if (length != 0) 
      { 
       cout << "[";//prints the end bracket 
       for (int i = 0; i < size(); i++){ 

        if (i == 0)//if the index is equal to the beginning of the list 
         cout << a1[0];//print the first item 
        else 
         cout << ", " << a1[i];//prints a comma before the item to seperate the items 
       } 
       cout << "]" << endl;//prints the end bracket 
      } 
      else 
      { 

       cout << "There is nothing in the array to print!" << endl;//lets the user know that the list is empty 
      } 
     } 



    }; 


}; 
#endif 

Когда я пытаюсь запустить его, я получаю эту ошибку: ошибка C2446: «:»: преобразование не из «Int» в «основных :: Params» на линии 86 Я полностью застрял на этом. У кого-нибудь есть предложения. У меня нет идеи. Что мне делать. Думаю, это может быть из-за t он шаблон, потому что он говорит, что он должен возвращать int, но это не так, потому что он работает с другими типами, поэтому, возможно, это просто с помощью структур. Примечание: строка 86 является функцией получения.

+1

Какая линия 86? – user2079303

+0

Извините, строка 86 является функцией get – AnonymousUser

ответ

1

NULL - тип указателя. Ваш T не является указателем. Вы не можете вернуть NULL вместо T. Вам нужно будет найти другой способ показать, что такой записи нет.

//      T  not T 
return length != 0 ? a1[i] : NULL; 
+0

Wait null определяется как 0, поэтому я не получаю, как это указатель типа – AnonymousUser

+0

О, ладно, спасибо за объяснение – AnonymousUser

+0

Когда я перехожу к определению, он определяется как ((void *) 0), но в любом случае ... даже если он был равен 0, как в стандарте, даже *, что * не относится к типу 'T'. Вам нужно вернуть тип 'T'. – nvoigt

3

Если T является Params, то это не работает:

inline T get(int i){ 
    return length != 0 ? a1[i] : NULL;//returns a[i] if the length is not 0 
} 

NULL макрос для 0 и Params не имеет конструктор, который принимает 0.

В C++ нет такой вещи, как «нулевой объект» (некоторые другие языки имеют эту концепцию, C++ - нет).

Вы должны переделать эту функцию, чтобы либо вернуть определенное значение (например, T(), построенный по умолчанию T), либо выбросить исключение.

Вы должны также проверить, что i находится в пределах массива, прежде чем делать a1[i]; и помните, что использование семейства функций malloc работает только тогда, когда T является типом «простой-старый», поскольку он не вызывает никаких конструкторов. Этот код будет непригодным для чего-либо, содержащего std::string, например.

1

В вашей функции get() значение NULL равно 0, которое является int. Компилятор говорит, что get() может возвращать int вместо типа Params в определенных случаях. Вместо этого вы можете добавить утверждение или исключение, чтобы гарантировать, что размер достаточно велик, прежде чем возвращать значение массива.

Смежные вопросы