Solved

Overloading operator==

Posted on 2000-02-19
13
305 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
Comment Utility
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
Comment Utility
bool operator==(ItemType other)

Try to rewrite it as:

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

Expert Comment

by:Wyn
Comment Utility
Sorry ,nietod.I dont see your comment because i'm writing my answer.
I withdraw it and you plz.
0
 

Author Comment

by:rround
Comment Utility
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
Comment Utility
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
Comment Utility
>> 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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:rround
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
It's taken me a while to understand these concepts, but thanks for all your comments and help.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
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 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.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now