2015-11-19 2 views
-1

ниже проблема в одном из заголовка кода:связанный список функции C++ ", который имеет тип non-class 'int'??

#include <iostream> 
#include <fstream> 
#include <string> 
#include "extPersonType.h" 
#include "orderedLinkedList.h" 

using namespace std; 

class addressBookType: public orderedLinkedListType 
{ 
public: 
    void print() const; 

    void printNameInTheMonth(int month); 
    void printInfoOf(string lName); 
    void printNamesWithStatus(string status); 

    void printNamesBetweenLastNames(string last1, 
            string last2); 

    void insertNode(const extPersonType& eP); 

    void searchName(string lName); 

    void saveData(ofstream&); 

    addressBookType(); 

private: 
    nodeType* searchList(string lName); 
}; 

void addressBookType::print() const 
{ 
    nodeType* current = first; 


    while (current != NULL) 
    { 
     current->info.printInfo(); 
     cout << endl; 
     current= current->link; 
    } 
} 

void addressBookType::printNameInTheMonth(int month) 
{ 
    nodeType* current = first; 

    while(current != NULL) 
    { 
     if (current->info.isMonth(month)) 
     { 
      current->info.print(); 
      cout << endl; 
     } 
     current = current->link; 
    } 
} 

void addressBookType::printInfoOf(string lName) 
{ 
    nodeType* location = searchList(lName); 

    if (location != NULL) 
     location->info.printInfo(); 
    else 
     cout << lName << " is not in address book." << endl; 
} 

void addressBookType::printNamesWithStatus(string status) 
{ 
    nodeType* current = first; 

    while (current != NULL) 
    { 
     if (current->info.isStatus(status)) 
     { 
      current->info.print(); 
      cout << endl; 
     } 
     current = current->link; 
    } 
} 

void addressBookType::printNamesBetweenLastNames(string last1, 
               string last2) 
{ 
    string lName; 

    nodeType* current = first; 

    while(current != NULL) 
    { 
     lName = current->info.getLastName(); 

     if (last1 <= lName && lName <= last2) 
     { 
      current->info.print(); 
      cout << endl; 
     } 
     current = current->link; 
    } 
} 

void addressBookType::insertNode(const extPersonType& eP) 
{ 
    orderedLinkedListType::insertNode(eP); 
} 

void addressBookType::searchName(string lName) 
{ 
    nodeType* location = searchList(lName); 

    if (location != NULL) 
     cout << lName << " is in the address book" << endl; 
    else 
     cout << lName << " is not in the address book" << endl; 
} 


nodeType* addressBookType::searchList(string lName) 
{ 
    nodeType* current = first; 
    bool found = false; 

    while (current != NULL) 
    { 
     if (current->info.isLastName(lName)) 
     { 
      found = true; 
      break; 
     } 

     current = current->link; 
    } 

    return current; 
} 

void addressBookType::saveData(ofstream& outFile) 
{ 
    string firstN; 
    string lastN; 

    int month; 
    int day; 
    int year; 

    string street; 
    string city; 
    string state; 
    string zip; 

    string phone; 
    string pStatus; 

    nodeType* current = first; 

    while (current != NULL) 
    { 
     current->info.getDOB(month, day, year); 
     current->info.getAddress(street,city,state,zip); 
     current->info.getPhoneNumber(); 
     current->info.getStatus(); 

     outFile << current->info.getFirstName() << " " 
<< current->info.getLastName() << endl; 
    outFile << month << " " << day << " " << year << endl; 
    outFile << street << endl << city << endl << state << endl << zip 
<< endl; 
    outFile << current->info.getPhoneNumber() << endl 
      << current->info.getStatus() << endl; 

    current = current->link; 
} 
} 


addressBookType::addressBookType() 
{ 
} 

эти два заголовка файла, который я подозреваю, что есть проблемы с ним, но они не имеют никаких ошибок на всех

#include <iostream> 

#include "linkedList.h" 

using namespace std; 


class orderedLinkedListType: public linkedListType 
{ 
public: 
bool search(const int& searchItem) const; 
    //Function to determine whether searchItem is in the list 
    //Postcondition: Returns true if searchItem is in the list; 
    //    otherwise, the value false is returned. 
void insertNode(const int& newItem); 
    //Function to insert newItem in the list 
    //Postcondition: first points to the new list and 
    //  newItem is inserted at the proper place in the list 
void deleteNode(const int& deleteItem); 
    //Function to delete deleteItem from the list 
    //Postcondition: If found, then the node containing the 
    //     deleteItem is deleted from the list; 
    //     first points to the first node of 
    //     the new list 
    //    If deleteItem is not in the list, 
    //     an appropriate message is printed 
void printListReverse() const; 
    //This function prints the list in reverse order 
    //Because the original list is in ascending order, the 
    //elements will be printed in descending order 

private: 
void reversePrint(nodeType *current) const; 
    //This function is called by the public member 
    //function to print the list in reverse order 
    }; 



bool orderedLinkedListType::search(const int& searchItem) const 
{ 
bool found = false; 
nodeType *current; //pointer to traverse the list 

current = first; //start the search at the first node 

while (current != NULL && !found) 
    if (current->info >= searchItem) 
     found = true; 
    else 
     current = current->link; 

if (found) 
    found = (current->info == searchItem); //test for equality 

return found; 
}//end search 



void orderedLinkedListType::insertNode(const int& newitem) 
{ 
nodeType *current; //pointer to traverse the list 
nodeType *trailCurrent; //pointer just before current 
nodeType *newNode; //pointer to create a node 

bool found; 

newNode = new nodeType; //create the node 
assert(newNode != NULL); 

newNode->info = newitem; //store newitem in the node 
newNode->link = NULL;  //set the link field of the node 
          //to NULL 

if (first == NULL) //Case 1 
{ 
    first = newNode; 
    count++; 
} 
else 
{ 
    current = first; 
    found = false; 

    while (current != NULL && !found) //search the list 
     if (current->info >= newitem) 
      found = true; 
     else 
     { 
      trailCurrent = current; 
      current = current->link; 
     } 

    if (current == first)  //Case 2 
    { 
     newNode->link = first; 
     first = newNode; 
     count++; 
    } 
    else      //Case 3 
    { 
     trailCurrent->link = newNode; 
     newNode->link = current; 

     count++; 
    } 
}//end else 
}//end insertNode 

    void orderedLinkedListType::deleteNode(const int& deleteItem) 
{ 
nodeType *current; //pointer to traverse the list 
nodeType *trailCurrent; //pointer just before current 
bool found; 

if (first == NULL) //Case 1 
    cout << "Cannot delete from an empty list." << endl; 
else 
{ 
    current = first; 
    found = false; 

    while (current != NULL && !found) //search the list 
     if (current->info >= deleteItem) 
      found = true; 
     else 
     { 
      trailCurrent = current; 
      current = current->link; 
     } 

    if (current == NULL) //Case 4 
     cout << "The item to be deleted is not in the " 
      << "list." << endl; 
    else 
     if (current->info == deleteItem) //item to be 
           //deleted is in the list 
     { 
      if (first == current)  //Case 2 
      { 
       first = first->link; 
       delete current; 
      } 
      else       //Case 3 
      { 
       trailCurrent->link = current->link; 
       delete current; 
      } 
      count--; 
     } 
     else       //Case 4 
      cout << "Item to be deleted is not in the " 
       << "list." << endl; 
} 
} //end deleteNode 


void orderedLinkedListType::reversePrint 
         (nodeType *current) const 
{ 
if (current != NULL) 
{ 
    reversePrint(current->link);  //print the tail 
    cout << current->info << " ";  //print the node 
} 
} 


void orderedLinkedListType::printListReverse() const 
{ 
reversePrint(first); 
cout << endl; 
} 

это второй один:

#include <iostream> 
#include <cassert> 
#include <assert.h> 

using namespace std; 

//Definition of the node 


struct nodeType 
{ 
int info; 
nodeType *link; 
}; 


class linkedListType 
{ 
public: 
const linkedListType& operator= 
        (const linkedListType&); 
    //Overload the assignment operator. 
void initializeList(); 
    //Initialize the list to an empty state. 
    //Postcondition: first = NULL, last = NULL, count = 0; 
bool isEmptyList() const; 
    //Function to determine whether the list is empty. 
    //Postcondition: Returns true if the list is empty, 
    //    otherwise it returns false. 
void print() const; 
    //Function to output the data contained in each node. 
    //Postcondition: none 
int length() const; 
    //Function to return the number of nodes in the list. 
    //Postcondition: The value of count is returned. 
void destroyList(); 
    //Function to delete all the nodes from the list. 
    //Postcondition: first = NULL, last = NULL, count = 0; 
int front() const; 
    //Function to return the first element of the list. 
    //Precondition: The list must exist and must not be 
    //    empty. 
    //Postcondition: If the list is empty, the program 
    //    terminates; otherwise, the first 
    //    element of the list is returned. 
int back()const; 
    //Function to return the last element of the list. 
    //Precondition: The list must exist and must not be 
    //    empty. 
    //Postcondition: If the list is empty, the program 
    //    terminates; otherwise, the last 
    //    element of the list is returned. 

bool search(const int& searchItem) const; 
    //Function to determine whether searchItem is in the list. 
    //Postcondition: Returns true if searchItem is in the 
    //    list, otherwise the value false is 
    //    returned. 

void insertFirst(const int& newItem); 
    //Function to insert newItem at the beginning of the list. 
    //Postcondition: first points to the new list, newItem is 
    //    inserted at the beginning of the list, 
    //    last points to the last node in the list, 
    //    and count is incremented by 1. 

void insertLast(const int& newItem); 
    //Function to insert newItem at the end of the list. 
    //Postcondition: first points to the new list, newItem 
    //    is inserted at the end of the list, 
    //    last points to the last node in the list, 
    //    and count is incremented by 1. 

void deleteNode(const int& deleteItem); 
    //Function to delete deleteItem from the list. 
    //Postcondition: If found, the node containing 
    //    deleteItem is deleted from the list. 
    //    first points to the first node, last 
    //    points to the last node of the updated 
    //    list, and count is decremented by 1. 


linkedListType(); 
    //default constructor 
    //Initializes the list to an empty state. 
    //Postcondition: first = NULL, last = NULL, count = 0; 

linkedListType(const linkedListType& otherList); 
    //copy constructor 

~linkedListType(); 
    //destructor 
    //Deletes all the nodes from the list. 
    //Postcondition: The list object is destroyed. 

protected: 
int count; //variable to store the number of 
      //elements in the list 
nodeType *first; //pointer to the first node of the list 
nodeType *last; //pointer to the last node of the list 

private: 
void copyList(const linkedListType& otherList); 
    //Function to make a copy of otherList. 
    //Postcondition: A copy of otherList is created and 
    //    assigned to this list. 
}; 



bool linkedListType::isEmptyList() const 
{ 
return(first == NULL); 
} 


linkedListType::linkedListType() //default constructor 
{ 
first = NULL; 
last = NULL; 
count = 0; 
} 


void linkedListType::destroyList() 
{ 
nodeType *temp; //pointer to deallocate the memory 
         //occupied by the node 
while (first != NULL) //while there are nodes in the list 
{ 
    temp = first;  //set temp to the current node 
    first = first->link; //advance first to the next node 
    delete temp;  //deallocate the memory occupied by temp 
} 
last = NULL; //initialize last to NULL; first has already 
      //been set to NULL by the while loop 
count = 0; 
} 


void linkedListType::initializeList() 
{ 
destroyList(); //if the list has any nodes, delete them 
} 


void linkedListType::print() const 
{ 
nodeType *current; //pointer to traverse the list 

current = first; //set current so that it points to 
        //the first node 
while (current != NULL) //while more data to print 
{ 
    cout << current->info << " "; 
    current = current->link; 
} 
}//end print 



int linkedListType::length() const 
{ 
return count; 
} //end length 


int linkedListType::front() const 
{ 
assert(last != NULL); 
return first->info; //return the info of the first node 
}//end front 


int linkedListType::back() const 
{ 
assert(last != NULL); 
return last->info; //return the info of the first node 
}//end back 



bool linkedListType::search(const int& searchItem) const 
{ 
nodeType *current; //pointer to traverse the list 
bool found = false; 

current = first; //set current to point to the first 
       //node in the list 

while (current != NULL && !found) //search the list 
    if (current->info == searchItem) //searchItem is found 
     found = true; 
    else 
     current = current->link; //make current point to 
           //the next node 
return found; 
}//end search 


void linkedListType::insertFirst(const int& newItem) 
{ 
    nodeType *newNode; //pointer to create the new node 

    newNode = new nodeType; //create the new node 

    assert(newNode != NULL);  //if unable to allocate memory, 
          //terminate the program 

    newNode->info = newItem;  //store the new item in the node 
    newNode->link = first;  //insert newNode before first 
    first = newNode;    //make first point to the 
          //actual first node 
    count++;    //increment count 

    if (last == NULL) //if the list was empty, newNode is also 
        //the last node in the list 
    last = newNode; 
    }//end insertFirst 


    void linkedListType::insertLast(const int& newItem) 
    { 
    nodeType *newNode; //pointer to create the new node 

    newNode = new nodeType; //create the new node 

    assert(newNode != NULL); //if unable to allocate memory, 
       //terminate the program 

    newNode->info = newItem;  //store the new item in the node 
    newNode->link = NULL;   //set the link field of newNode 
         //to NULL 

    if (first == NULL) //if the list is empty, newNode is 
       //both the first and last node 
    { 
    first = newNode; 
    last = newNode; 
    count++;  //increment count 
    } 
    else  //the list is not empty, insert newNode after last 
    { 
    last->link = newNode; //insert newNode after last 
    last = newNode; //make last point to the actual last node 
    count++;  //increment count 
    } 
    }//end insertLast 



void linkedListType::deleteNode(const int& deleteItem) 
{ 
nodeType *current; //pointer to traverse the list 
nodeType *trailCurrent; //pointer just before current 
bool found; 

if (first == NULL) //Case 1; the list is empty. 
    cout << "Cannot delete from an empty list." 
     << endl; 
else 
{ 
    if (first->info == deleteItem) //Case 2 
    { 
     current = first; 
     first = first->link; 
     count--; 
     if (first == NULL) //the list has only one node 
      last = NULL; 
     delete current; 
    } 
    else //search the list for the node with the given info 
    { 
     found = false; 
     trailCurrent = first; //set trailCurrent to point 
           //to the first node 
     current = first->link; //set current to point to 
           //the second node 

     while (current != NULL && !found) 
     { 
      if (current->info != deleteItem) 
      { 
       trailCurrent = current; 
       current = current-> link; 
      } 
      else 
       found = true; 
     }//end while 

     if (found) //Case 3; if found, delete the node 
     { 
      trailCurrent->link = current->link; 
      count--; 

      if (last == current) //node to be deleted 
            //was the last node 
       last = trailCurrent; //update the value 
            //of last 
      delete current; //delete the node from the list 
     } 
     else 
      cout << "The item to be deleted is not in " 
       << "the list." << endl; 
    }//end else 
}//end else 
}//end deleteNode 


void linkedListType::copyList 
       (const linkedListType& otherList) 
{ 
nodeType *newNode; //pointer to create a node 
nodeType *current; //pointer to traverse the list 

if (first != NULL) //if the list is nonempty, make it empty 
    destroyList(); 

if (otherList.first == NULL) //otherList is empty 
{ 
    first = NULL; 
    last = NULL; 
    count = 0; 
} 
else 
{ 
    current = otherList.first; //current points to the 
           //list to be copied 
    count = otherList.count; 

     //copy the first node 
    first = new nodeType; //create the node 

    assert(first != NULL); 

    first->info = current->info; //copy the info 
    first->link = NULL;  //set the link field of 
           //the node to NULL 
    last = first;    //make last point to the 
           //first node 
    current = current->link;  //make current point to 
           //the next node 

     //copy the remaining list 
    while (current != NULL) 
    { 
     newNode = new nodeType; //create a node 

     assert(newNode != NULL); 

     newNode->info = current->info; //copy the info 
     newNode->link = NULL;  //set the link of 
            //newNode to NULL 
     last->link = newNode; //attach newNode after last 
     last = newNode;  //make last point to 
           //the actual last node 
     current = current->link; //make current point 
            //to the next node 
    }//end while 
}//end else 
}//end copyList 


linkedListType::~linkedListType() //destructor 
{ 
    destroyList(); 
}//end destructor 


linkedListType::linkedListType 
       (const linkedListType& otherList) 
{ 
first = NULL; 
copyList(otherList); 
}//end copy constructor 

    //overload the assignment operator 

const linkedListType& linkedListType::operator= 
        (const linkedListType& otherList) 
{ 
if (this != &otherList) //avoid self-copy 
{ 
    copyList(otherList); 
}//end else 

return *this; 
} 

я получил ошибку говоря об ошибке: запрос для члена «Принтинфо» в «current-> NODETYPE :: Информация», которая является не-класса типа «Int» , Есть еще несколько файлов заголовков, связанных с этим заголовком, которые имеют кодировку шаблонов. Однако мне удалось удалить кодировку шаблонов из всех других заголовков без ошибок вообще, за исключением этого заголовка. может ли кто-нибудь сказать мне, как его решить?

+3

Ошибка говорит все - ваша информация в классе nodeType является int, а не классом. – SergeyA

+0

Как определяются 'nodeType :: info' и' nodeType'? – myaut

+2

Пожалуйста, ** ** ваш вопрос с помощью [mcve] или [SSCCE (Short, Self Contained, Correct Example)] (http://sscce.org) – NathanOliver

ответ

2

Вы определили struct nodeType с членом int info;. Но в addressBookType::printInfoOfaddressBookType::print) у вас есть линия location->info.printInfo();

Поскольку info является int, он не имеет методов для вызова, printInfo или иначе, таким образом ошибку.

Похоже, проблема связана с несоответствием другого типа в вашем коде. addressBookTypeinsertNode принимает const extPersonType& (который, как я полагаю, определен в другом месте и реализует методы, которые вы пытаетесь использовать?), Но передает его orderedLinkedListType::insertNode, который берет и хранит const int&. Обычно это не сработает, но при догадке extPersonType - это тип (возможно, C++ 11 строго типизированный enum), который имеет неявное преобразование в int, что может избежать ошибок компиляции во время назначения, но по-прежнему эффективно блокирует все extPersonType -специфическое поведение на insertNode, оно идет от extPersonType до всего лишь int.

Если вы хотите связанный список общего назначения, вам необходимо создать шаблон для работы с более чем int, например. изменение nodeType к:

template<typename T> 
struct nodeType { 
    T info; 
    nodeType<T> *link; 
}; 

и обновляя все методы, связанные с nodeType и orderedLinkedListType в шаблон в зависимости от обстоятельств к определенному типу, а не int. Если вы ленитесь, вместо этого вы можете просто изменить все виды использования int в nodeType и orderedLinkedListType до extPersonType, но теперь код не подходит для int s, поэтому выберите свой яд.

+0

Значит, член структуры nodetype следует изменить? Есть ли какое-либо обходное решение, если я хочу сохранить информацию как int? –

+0

@LingShiWu: Думаю, вам нужно выяснить, что должен делать 'printInfo', и что должны хранить узлы связанного списка. Я не вижу никакого определения 'printInfo', и похоже, что ваш' addressBookType' предполагает, что связанный список хранит 'extPersonType' как' info', а не 'int'. Обычно связанный список определяется шаблоном, поэтому данные, хранящиеся в каждом узле, не фиксируются заголовком, например. 'template struct nodeType { T info; nodeType * link; }; 'или тому подобное, чтобы вы могли хранить' int' или 'extPersonType', если это необходимо. – ShadowRanger

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