Отсутствуют аргументы шаблона перед '.' знак - PullRequest
3 голосов
/ 04 ноября 2011

Я пытаюсь организовать свою программу в функции и столкнулся с такой ошибкой:

: "отсутствуют аргументы шаблона перед '."token "

как только я пытаюсь запустить код в функции, он работает нормально, если его просто в main().Кто-нибудь, кто знаком с этой ошибкой, знает, в чем может быть проблема?

Обратите внимание: закомментированный код удаляет ошибку, но мешает упорядоченному списку class и сбрасывает его длину или что-то еще, вызывая функцию orderedlist.getlength()return 0, что не позволяет выполнить ни один из кодов в цикле while().

функция :

void rentFilm(char* filmId, char* custId, char* rentDate, char* dueDate, int numFilm)
{
    //orderedList <filmType> orderedList(numFilm);
    //filmType newItem;
    int index = 0;
    bool found = false;

    while (index < orderedList.getLength() && !found)
        {
            cout << "test" << endl;
        if (strncmp(filmId,orderedList.getAt(index).number,6) == 0 && strncmp("0000",orderedList.getAt(index).rent_id,5) == 0)//If that film is rented by NO customer
            {
                cout << "test" << endl;
                found = true;//customer can rent it
                strcpy(newItem.number,filmId);
                orderedList.retrieve(newItem);
                orderedList.remove(newItem);
                strcpy(newItem.rent_id,custId);
                strcpy(newItem.rent_date,rentDate);
                strcpy(newItem.return_date,dueDate);
                orderedList.insert(newItem);
                cout << "Rent confirmed!" << endl;
            }
        else
            {
                if (strncmp(filmId,orderedList.getAt(index).number,6) > 0 || strncmp("0000",orderedList.getAt(index).rent_id,5) > 0)
                    {
                        ++ index;
                    }
                else
                    {
                     throw string ("Not in list");
                    }
            }
        }
}

Вставить в класс orderList (гдедлина определена) :

template <class elemType>
void orderedList<elemType>::insert(const elemType& newItem)
{
     int index = length - 1;
     bool found = false;

     if (length == MAX_LIST)
         throw string ("List full - no insertion");

         // index of rear is current value of length

     while (! found && index >= 0)
        if (newItem < list[index])
        {
            list[index + 1] = list [index];  // move item down
            --index;
        }
        else
            found = true;

     list [index + 1] = newItem;  // insert new item
     ++length;
}

код в основном, где заполнен список:

filmFile.open("films.txt", ios::in);
filmFile >> numFilm;
filmFile.get();

orderedList <filmType> orderedList(numFilm);
filmType newItem;

readString(filmFile, newItem.number,5);
    for (int i = 0; i < numFilm; i++)
    {
         newItem.copy = filmFile.get();
     readString(filmFile, newItem.title,30);
         readString(filmFile, newItem.rent_id,4);
         readString(filmFile, newItem.rent_date,8);
         readString(filmFile, newItem.return_date,8);
         filmFile.get();

         orderedList.insert (newItem);//puts filmType struct into the ordered list.

         readString(filmFile, newItem.number,5);
    }

Пожалуйста, дайте мне знать, если код откуда-либо еще вПрограмма будет полезна для оценки этой ошибки.

Ответы [ 3 ]

1 голос
/ 04 ноября 2011

Похоже, что строка, которую вы закомментировали, объявляет переменную с тем же именем, что и класс.

Поэтому, когда вы это комментируете, статические функции этого класса вызываются.

Измените объявление на что-то вроде:

orderedList<filmType> filmList(numFilm);

, а затем измените все ссылки orderedList в функции на filmList.

0 голосов
/ 04 ноября 2011

Кажется, что вы заполняете переменную orderedList в main(), а затем ожидаете, что она будет автоматически доступна в rentFilm(...) при объявлении с тем же именем;это невозможно.Вы должны передать объект в функцию из main() или лучше, чтобы сделать эту функцию как метод-член class orderedList:

int main ()
{
  orderedList<filmType> ol(numFilm); // variable name different (good practice)
  ... // all the populating
  orderedList.rentFilm(...);  // call the function like this
}

, где rentFilem() теперь является частью class

class orderedList {
...
public:
  void rentFilm(char* filmId, char* custId, char* rentDate, char* dueDate, int numFilm);
};

Теперь внутри функции вам не нужно объявлять переменную для orderedList;просто используйте this-><method/variable>.Это должно работать.

0 голосов
/ 04 ноября 2011

Проблема в том, что вы создаете переменную с тем же именем, что и шаблон? Когда вы говорите,

orderedList<filmType> orderedList(numFilm);

это (вроде) как сказать,

int int=42;

и ожидание возврата int+1 43

Попробуйте что-то вроде,

orderedList<filmType> ol(numFilm);

И изменить все другие ссылки на orderedList, на ol.

...