Solved

Overloading operator==

Posted on 2000-02-19
13
310 Views
Last Modified: 2010-04-02
I have a question about overloading operator== within a template class.  Here is a copy of my code so far.  I just can't seem to get this function to compile without errors.  Eventually, I want to be able to compare the strings held in MyAddress.name while searching the list.  I may be completely off track here so any assistance would be appreciated.

Thanks.


#include<iostream.h>
#include<stdlib.h>

template<class ItemType>
struct NodeType
      {
      ItemType info;
      NodeType *next;
      };


template<class ItemType>
class ListClass
{

public:

      // Constructor and Destructor
      ListClass()
      {
      cout << "Class Constructor Running." << endl;
      length = 0;
      listData = NULL;
      }


      ~ListClass()
      {
      cout << "Class Destructor Running." << endl;
      MakeEmpty();
      }

      
      void MakeEmpty()
      {
      cout << "MakeEmpty() is running" << endl;
      NodeType<ItemType>* tempPtr;
      while (listData != NULL)
            {
            tempPtr = listData;
            listData = listData -> next;
            delete tempPtr;
            }
      length = 0;
      }

      
      bool operator==(ItemType other)
      {
            NodeType<ItemType> temp;

            //return (temp.name, other.name)?false:true;
      }


      void FindItem(ItemType& item, bool& foundIt)
      {
            bool more;
            NodeType<ItemType>* location;

            location = listData;
            foundIt = false;
            more = (location != NULL);

            while (more && !foundIt)
            {
                  if (item == location -> info)
                  {
                        foundIt = true;
                        item = location -> info;
                  }
                  else
                  {
                        location = location -> next;
                        more = (location != NULL);
                  }
            }
      }
            

      bool IsEmpty() const
      {
      return (length == 0);
      }

      
      bool IsFull() const
      {
      NodeType<ItemType>* ptr;
      ptr = new NodeType<ItemType>;
      if (ptr == NULL)
            return true;
      else
            {
            delete ptr;
            return false;
            }
      }

      
      int LengthIs() const
      {
            return length;
      }

      
      void InsertItem(ItemType newItem)
      {
            NodeType<ItemType>* location;

            location = new NodeType<ItemType>;
            location -> info = newItem;
            location -> next = listData;
            listData = location;
            length++;
      }


      void DeleteItem(ItemType item)
      {
            NodeType<ItemType>* location = listData;
            NodeType<ItemType>* tempLocation;

            if (item == listData -> info)
            {
                  tempLocation = location;
                  listData = listData -> next;
            }
            else
            {
                  while (!(item == (location -> next) -> info))
                        location = location -> next;
            
                  tempLocation = location -> next;
                  location -> next = (location -> next) -> next;
            }
            delete tempLocation;
            length--;
            }


private:
      int length;
      NodeType<ItemType>* listData;
      NodeType<ItemType>* currentPosition;

};



#include <fstream.h>

struct Address
{
      char name[50];
      char streetAddress[50];
      char city[50];
      char phone[15];
};

void main()
{

      Address MyAddress;

      ListClass<Address> myList;
      myList.MakeEmpty();

      fstream inData("input.dat", ios::in);

      while (!inData.eof())
      {
      inData.getline(MyAddress.name, 50);
      inData.getline(MyAddress.streetAddress, 50);
      inData.getline(MyAddress.city, 50);
      inData.getline(MyAddress.phone, 15);

      myList.InsertItem(MyAddress);
      }
      
// print contents of list to screen and delete from list
while (!myList.IsEmpty())
      {
      cout << endl;
      cout << MyAddress.name << endl;
      cout << MyAddress.streetAddress << endl;
      cout << MyAddress.city << endl;
      cout << MyAddress.phone << endl;
      myList.DeleteItem(MyAddress);

      }
      cout << endl;
      inData.close();
}
0
Comment
Question by:rround
  • 4
  • 4
  • 2
  • +2
13 Comments
 
LVL 22

Expert Comment

by:nietod
ID: 2538508
I'm not sure how you want operator == to work.  i.e what are the conditions under which two ListClass objects are considered equal? You have to figure that out (depending on what your needs are), then its not to hard to write the operator.  I woudl make the following changes.  Both parameters to the operator should be constant so write it like

bool operator==(const ItemType &other) const
{
   // what di you want to test for here?
}
0
 
LVL 5

Expert Comment

by:Wyn
ID: 2538510
bool operator==(ItemType other)

Try to rewrite it as:

bool operator==(ItemType& other)
....
0
 
LVL 5

Expert Comment

by:Wyn
ID: 2538511
Sorry ,nietod.I dont see your comment because i'm writing my answer.
I withdraw it and you plz.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rround
ID: 2538518
Somehow, I want to pass the char array name from the struct and compare it to a string that the user enters.  So basically I'll be searching the list for a string. If it finds a matching string, the whole struct gets passed back.  This way you can search for an address by using a name.
0
 
LVL 22

Expert Comment

by:nietod
ID: 2538519
returning a success/error indicator via a reference parameter like

void FindItem(ItemType& item, bool& foundIt)

is often inconvenient for the code calling the function.  Instead use a return value.  Also since the fucntion doesn;t change the list object, it should be constant, like

bool FindItem(Itemtype &Item) const.

In

bool IsFull() const
{
   NodeType<ItemType>* ptr;
   ptr = new NodeType<ItemType>;
   if (ptr == NULL)
      return true;
   else
   {
      delete ptr;
      return false;
   }
}

What the @$#$% are you doing?  Why are you creating and deleting a node?

In

void InsertItem(ItemType newItem)

you can pass the itemType as a constant reference, like

void InsertItem(const ItemType &newItem)

Same with

void DeleteItem(ItemType item)
0
 
LVL 22

Expert Comment

by:nietod
ID: 2538526
>> I want to pass the char array name from the
>> struct and compare it to a string that the user
>> enters.  So basically I'll be searching the list for
>> a string. If it finds a matching string, the whole
>> struct gets passed back.  This way you can
>> search for an address by using a name.
What character array?  A listClass will be on the left side of the operator.  Do you not want a ListClass on the right?  i.e. do you want a string (character array) on the right?
0
 

Author Comment

by:rround
ID: 2538530
bool IsFull() const
{
   NodeType<ItemType>* ptr;
   ptr = new NodeType<ItemType>;
   if (ptr == NULL)
      return true;
   else
   {
      delete ptr;
      return false;
   }
}

What the @$#$% are you doing?  Why are you creating and deleting a node?

I took this directly from the book??  It made sense to me, my instructor said we had to delete this stuff.
0
 
LVL 22

Expert Comment

by:nietod
ID: 2538537
What is the point of what it is trying to do.  From the function name it sounds like it is to determine if the container is full.  But a linked list container can never be full.  What is more the code is garbage.  it will always return false.  Which is good since a linked list can naver be full, but why go to all that trouble to return false.

the code looks like it may rely on the fact that new returns NULL when it runs out of memory.  But that is not true.  It was true about 6 or 8 years ago, but not any more.
0
 

Author Comment

by:rround
ID: 2538544
Maybe I need to make my intentions clearer.  In both FindItem() and DeleteItem() I have an == operation.  The project required the use of a template that's why I have used it.  I declared a struct Address.  Within Address is the character array name, address etc. The struct Address is placed in the and I somehow need to search the list matching the name field of the struct with the user input.  This is kind of confusing to me so I may be completely off track with the way I'm trying to accomplish this.

Thanks.
0
 
LVL 14

Accepted Solution

by:
AlexVirochovsky earned 100 total points
ID: 2538547
Next is you text

#include<iostream.h>
#include<stdlib.h>

template <class ItemType>
struct NodeType
{
  ItemType info;
  NodeType *next;
};

template<class ItemType>
class ListClass
{
  public:

 // Constructor and Destructor
 ListClass()
  {
    cout << "Class Constructor Running." << endl;
    length = 0;
    listData = NULL;
  }


  ~ListClass()
   {
     cout << "Class Destructor Running." << endl;
     MakeEmpty();
   }


   void MakeEmpty()
     {
       cout << "MakeEmpty() is running" << endl;
       NodeType<ItemType>* tempPtr;
       while (listData != NULL)
        {
          tempPtr = listData;
          listData = listData -> next;
          delete tempPtr;
        }
       length = 0;
     }
    bool operator==(const ItemType& other) const
      {
        return listData->info == other ? false : true;
      }

    void FindItem(ItemType& item, bool& foundIt)
      {
        bool more;
        NodeType <ItemType>* location;

        location = listData;
        foundIt = false;
        more = (location != NULL);

        while (more && !foundIt)
          {
            if (item == location->info) //changed
              {
                foundIt = true;
                item = location->info;//changed
              }
            else
              {
                location = location->next; //changed
                more = (location != NULL);
              }
          }
      }

   bool IsEmpty() const
    {
     return (length == 0);
    }




bool IsFull() const
{
   NodeType<ItemType>* ptr;
   ptr = new NodeType<ItemType>;
   if (ptr == NULL)
     return true;
   else
    {
      delete ptr;
      return false;
    }
}


int LengthIs() const
{
return length;
}


void InsertItem(ItemType newItem)
{
NodeType<ItemType>* location;

location = new NodeType<ItemType>;
location -> info = newItem;
location -> next = listData;
listData = location;
length++;
}


void DeleteItem(ItemType item)
{
  NodeType<ItemType>* location = listData;
  NodeType<ItemType>* tempLocation;

  if (item == listData -> info)
    {
      tempLocation = location;
      listData = listData -> next;
    }
   else
    {
      while (!(item == (location->next)->info))
         location = location->next;

      tempLocation = location->next;
      location->next = (location->next)->next;
    }
  delete tempLocation;
  length--;
}


private:
int length;
NodeType<ItemType>* listData;
NodeType<ItemType>* currentPosition;

};



#include <fstream.h>

class Address
{
  public:

  int operator == ( const Address& ) const;
  char name[50];
  char streetAddress[50];
  char city[50];
  char phone[15];
};
int Address::operator == ( const Address& test ) const
{
    return stricmp(name,test.name);
}

void main()
{

Address MyAddress;

ListClass <Address> myList;
myList.MakeEmpty();

fstream inData("input.dat", ios::in);

while (!inData.eof())
{
inData.getline(MyAddress.name, 50);
inData.getline(MyAddress.streetAddress, 50);
inData.getline(MyAddress.city, 50);
inData.getline(MyAddress.phone, 15);

myList.InsertItem(MyAddress);
}

// print contents of list to screen and delete from list
while (!myList.IsEmpty())
{
cout << endl;
cout << MyAddress.name << endl;
cout << MyAddress.streetAddress << endl;
cout << MyAddress.city << endl;
cout << MyAddress.phone << endl;
myList.DeleteItem(MyAddress);

}
cout << endl;
inData.close();
}

I hope, it helps. Alex
0
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 2538552
O , i see full discussion. I don't sure, that that code works! But translation, as rround asks, without
errors.
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 2542928
Could very well be what is needed. If you use an operator like == on the type argument of a template, that operator must be defined for that type. As ALex shows.
0
 

Author Comment

by:rround
ID: 2542982
It's taken me a while to understand these concepts, but thanks for all your comments and help.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question