Trouble with overloaded '==' operator

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 1139 Views - Last Post: 11 March 2013 - 05:32 PM Rate Topic: -----

#1 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Trouble with overloaded '==' operator

Posted 10 March 2013 - 04:55 PM

This is a homework project that I am doing that combines use of inheritance, recursion, templates, and overloaded operators into one. I am having some trouble with my '==' operator not working correctly. I am getting the error: "error C2679: binary '==' : no operator found which takes a right-hand operand of type 'P03::Person' (or there is no acceptable conversion)"


My code is lengthy so if it is against the norm to post the full code here, I can revise it to snippets or put it on a pastebin.

Person header

/* File: Person.h
 *
 * The class representing a Person.
 */
#ifndef PERSON_H
#define PERSON_H

#include <string>
#include <iostream>

using namespace std;

namespace P03 {
	class Person {
	
	private:
		string firstName;
		string lastName;

	public:
		/* Initializes the object.
		 */
		Person(const string& firstName = "na", const string& lastName = "na");

		/* Getter methods retun the field value.
		 */
		string getFirstName() const;
		string getLastName() const;

		/* Gets the name
		*/
		string getKeyValue() const;

		/* Returns the compound value: <lastName><space><firstName>
		 */
		string getName() const;

		/* Setter methods, set the object.
		 */
		void setFirstName(const string& firstName);
		void setLastName(const string& lastName);


		/* Returns the object formatted as:
		*  Person{ firstName=<firstName>, lastName=<lastName> }
		*/
		virtual string toString() const;
	}; // end Person


	/* Displays a Person to the screen.
	 * Calls the toString() method.
	 */
	ostream& operator <<(ostream& out, const Person& person)
	{
		return out << person.toString();
	}

	/* The following relational operators compare two instances of the
	 * Person class. The comparison is made on the compound value of:
	 * <lastName><space><firstName>
	 */
	bool operator ==(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() == rhs.getName();
	}

	bool operator ==(const char*& lhs, const Person& rhs)
	{
		return lhs == rhs.getName();
	}

	bool operator !=(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() != rhs.getName();
	}

	bool operator <(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() < rhs.getName();
	}

	bool operator <=(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() <= rhs.getName();
	}

	bool operator >(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() > rhs.getName();
	}

	bool operator >=(const Person& lhs, const Person& rhs)
	{
		return lhs.getName() >= rhs.getName();
	}

} // end namespace P03

#endif


Person cpp
/*    File: Person.cpp
 *    Name: Bryan Orabutt
 * Revised: 3/08/2013
 *  Course: CS240 - Introduction to Computing III - Spring 13
 * 
 *    Desc: Definitions file for the Person class.
 */

#include <string>
#include <iostream>
#include"Person.h"

namespace P03
{
	/* Constructor
	*  Creates a person with an optional first/last name.
	*/
	Person::Person(const string& firstName, const string& lastName)
	{
		this->firstName = firstName;
		this->lastName = lastName;
	}

	/* Gets the first name of the person.
	*/
	string Person::getFirstName() const
	{
		return firstName;
	}
	
	/* Gets the last name of the person.
	*/
	string Person::getLastName() const
	{
		return lastName;
	}

	/* Gets the first and last name.
	*/
	string Person::getName() const
	{
		string name = firstName;
		
		return name + " " + lastName;
	}

	/* Gets the key value for a Person (name).
	*/
	string Person::getKeyValue() const
	{
		return firstName + " " + lastName;
	}

	/* Sets the first name to the given value.
	*/
	void Person::setFirstName(const string& firstName)
	{
		this->firstName = firstName;
	}

	/* Sets the last name ot the given value.
	*/
	void Person::setLastName(const string& lastName)
	{
		this->lastName = lastName;
	}


	/* Displays a string representation of the person,
	*  showing their first and last names in a formatted fashion.
	*/
	string Person::toString() const
	{
		string desc = "Person{ firstName=" + firstName + ",";
		desc += " lastName=" + lastName + " }";

		return desc;
	}
}


main
/*    File: main.cpp
 *    Name: Bryan Orabutt
 * Revised: 3/08/2013
 *  Course: CS240 - Introduction to Computing III - Spring 13
 * 
 *    Desc: This program demostrates the use of inheritence, recursion, and 
 *    different sorting/searching algorithms.
 */

#include "Algorithm.h"
#include "Customer.h"
#include "Person.h"
#include "Employee.h"
#include <iostream>

using namespace std;
using namespace P03;


int main() {
	Customer* customer[] = { new Customer(1002, 100000.50, "F4", "L1"),
		                     new Customer(1004, 45000.90, "F1", "L3"),
							 new Customer(1003, 120000, "F3", "L2"),
							 new Customer(1001, 340000, "F2", "L4")
	                       };

	Employee* employee[] = { new Employee(102, 65000, "F2", "L1"),
		                     new Employee(104, 45000, "F4", "L3"),
							 new Employee(103, 120000, "F1", "L2"),
							 new Employee(101, 35000, "F3", "L4")
	                       };

	Person* person[] = { customer[0],
		                 customer[3],
						 employee[3],
						 employee[0],
						 employee[2],
						 customer[1],
						 employee[1],
						 customer[2]
					   };
	// Display the original arrays.
	cout << "Customer list:" << endl;
	display(customer, 4);

	cout << endl << "Employee list:" << endl;
	display(employee, 4);

	cout << endl << "Person list:" << endl;
	display(person, 8);


	// Sort the customer array.
	selectionSort(customer, 4);
	cout << endl << "Sorted customer list:" << endl;
	display(customer, 4);

	// Sort the employee array.
	selectionSort(employee, 4);
	cout << endl << "Sorted employee list:" << endl;
	display(employee, 4);

	// Sort the person array.
	selectionSort(person, 8);
	cout << endl << "Sorted person list: " << endl;
	display(person, 8);

	// Search the customer array.
	cout << endl
		 << "Searching customer array for customer with cId = 1002: "
		 << (binarySearch(customer, 1002, 0, 3) != -1? "found it." : "did not find it.")
		 << endl;

	// Search the employee array.
	cout << "Searching employee array for employee with eId = 105: "
		 << (binarySearch(employee, 105, 0, 3) != -1? "found it." : "did not find it.")
		 << endl;

	// Search the person array. //this line is the one the debugger flags as the cause of the error
	cout << "Searching people array for person with name = 'Mickey Mouse': "
		 << (binarySearch(person, "Mickey Mouse", 0, 7) != -1? "found it." : "did not find it.")
		 << endl;

	return 0;
}


algorithms header
/* File: Algorithm.h
 *
 * The recursive binary search, selection sort, and display prototypes.
 * You must provide inline implementations for all the functions.
 * The comparison is made by calling the getKeyValue() method on each 
 * array element.
 */

#ifndef SEARCH_H
#define SEARCH_H

namespace P03 {
	/* Performs a recursive binary search on the given array. It returns
	 * the index of the found value, -1 otherwise. 
	 */
	template <typename T, typename V>
	int binarySearch(T* list[], const V& searchValue,
		             const int firstIndex, const int lastIndex) 
	{ 
		if (firstIndex <= lastIndex) 
		{
			int mid = (firstIndex + lastIndex) / 2;  //mid point of list.
			if (searchValue == *list[mid]) 
				return mid;   // found value.
			else if (searchValue < *list[mid]) 
				return binarySearch(list, firstIndex, mid - 1, searchValue);
			else
				return binarySearch(list, mid + 1, lastIndex, searchValue);
		}
		return -1;    //failed to find value
	}

	/* The selection sort algorithm.
	 */
	template <typename T>
	void selectionSort(T* list[], const int length) 
	{ 
		int min;
		for (int j = 0; j < length - 1; j++) 
		{
			min = j; //assume min is first.
			for (int i = j + 1; i < length; i++) 
			{ 
				if (list[i] < list[min]) //tests if element is smaller
				{
					min = i; //sets new min if true
				}
			}
		if (min != j ) 
		{
			swapElements(list, j, min);
		}//end if
		}//end for
	}

	/* Finds the index of the smallest item.
	*/
	template <typename T>
	int indexOfSmallestElement(const int startIndex, T* list[], const int length) 
	{
		int min = 0;
		for(int i = startIndex; i < length; i++)
		{
			if(list[i] < min)
				min = i;
		}

		return min;
	}

	/* Swaps two elements in an array.
	*/
	template <typename T>
	void swapElements(T* list[], const int index1, const int index2) 
	{
		T temp = list[index1]; //holds first item
		list[index1] = list[index2];
		list[index2] = temp;
	}


	/* Displays each element of the array, one per line. It makes use
	 * of the overloaded <<() function.
	 */
	template <typename T>
	void display(T* list[], const int length) 
	{ 
		for(int i = 0; i < length; i++)
			cout << list[i];
	}
} // end namespace P03

#endif


There are two more classes as well but to shorten things I will not post them since the error message nor the degbugger seem to imply anything wrong with them. I should also note that I am not allowed to change anything in the main, or any of the .h files (aside from the alogrithms.h and the operators in the person.h)

Is This A Good Question/Topic? 0
  • +

Replies To: Trouble with overloaded '==' operator

#2 #define  Icon User is online

  • Duke of Err
  • member icon

Reputation: 1345
  • View blog
  • Posts: 4,633
  • Joined: 19-February 09

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 05:36 PM

You only declare functions in the implementation file, except inline functions in classes.

Try moving the function declarations into the cpp file, and writing the corresponding function prototypes (heads) in the header file.
Was This Post Helpful? 0
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,517
  • Joined: 23-August 08

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 05:37 PM

It's been a while for me, but shouldn't your overloaded arithmetic operators be members of the Person class?
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,117
  • Joined: 05-May 12

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 05:55 PM

The don't have to be if they don't access any private members of the class.
Was This Post Helpful? 1
  • +
  • -

#5 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 05:59 PM

Replacing the definitions with prototypes in my header and moving the definitions to the cpp did not solve the problem. Still have the same error. Im still just baffled as to what could be causing this.

Replacing the definitions with prototypes in my header and moving the definitions to the cpp did not solve the problem. Still have the same error. Im still just baffled as to what could be causing this.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,117
  • Joined: 05-May 12

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 06:31 PM

Which line is the error on?
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,117
  • Joined: 05-May 12

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 06:43 PM

Nevermind, I found the problem. You declared your function this way:
 template <typename T, typename V>
    int binarySearch(T* list[], const V& searchValue,
                     const int firstIndex, const int lastIndex)



but use it this way.
binarySearch(customer, 1002, 0, 3)



You have no == operator that compares the integer 1002 against a Customer class. (T is a Customer object, while V is an integer.)
Was This Post Helpful? 0
  • +
  • -

#8 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 06:46 PM

Line 23 of the algorithms.h file. This line here:

if (searchValue == *list[mid]) 


The debugger also says that its caused by this line in main:

// Search the person array.
	cout << "Searching people array for person with name = 'Mickey Mouse': "
		 << (binarySearch(person, "Mickey Mouse", 0, 7) != -1? "found it." : "did not find it.")
		 << endl;

Was This Post Helpful? 0
  • +
  • -

#9 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 06:58 PM

View PostSkydiver, on 10 March 2013 - 06:43 PM, said:

You have no == operator that compares the integer 1002 against a Customer class. (T is a Customer object, while V is an integer.)


Hmmm I see what you mean. Then this is an issue I'll have to take up with my instructor tomorrow. He explicitly told us we can not add any new functions and can not modify any of the ones he gave us in the header files. Either he made a mistake and there needs to be a modified and/or new == operator or there is some way of doing this with my current implementation that I am unaware of.
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,117
  • Joined: 05-May 12

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 07:47 PM

Yes, there is... have another operator ==() that takes a Customer and an int; and one that takes an Employee and an int; and one that takes a Person and a string.
Was This Post Helpful? 0
  • +
  • -

#11 #define  Icon User is online

  • Duke of Err
  • member icon

Reputation: 1345
  • View blog
  • Posts: 4,633
  • Joined: 19-February 09

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 08:01 PM

You have this in Person.

	bool operator ==(const char*& lhs, const Person& rhs)
	{
		return lhs == rhs.getName();
	}




Are you allowed to change the Person.h/Person.cpp?

Are you allowed to change Customer.h/Customer.cpp and Employee.h/Employee.cpp?

Are you writing Algorithm?
Was This Post Helpful? 0
  • +
  • -

#12 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 08:11 PM

View Post#define, on 10 March 2013 - 08:01 PM, said:

Are you allowed to change the Person.h/Person.cpp?

Are you allowed to change Customer.h/Customer.cpp and Employee.h/Employee.cpp?

Are you writing Algorithm?


I am unable to change and .h files except for Algorithm. I wrote all of the defintions for Algorithm, only the skeleton was given to me. I can't change any function names or arguments in Algorithm, nor can I add more functions. I can only rewrite my definitions for the functions already in there.

I can change the CPPs, but only using the functions given in their respective headers if that makes sense. I cant add a new operator == to any headers.
Was This Post Helpful? 0
  • +
  • -

#13 #define  Icon User is online

  • Duke of Err
  • member icon

Reputation: 1345
  • View blog
  • Posts: 4,633
  • Joined: 19-February 09

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 08:25 PM

Try adding the include files to Algorithim.h.

#include "Person.h"




Using this way of calling while debugging might give you more information :

      if ( operator==(searchValue, *list[mid]) )


Was This Post Helpful? 0
  • +
  • -

#14 FriendlyHobo  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 10-March 13

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 09:49 PM

Adding the include statement did not alleviate the error message. However, changing the if statement like you suggested did give me more info, but merely seems to confirm to me that Im going to need to change the arguments for my operators.

This is the error message I am getting now: error C2665: 'P03::operator ==' : none of the 3 overloads could convert all the argument types
Was This Post Helpful? 0
  • +
  • -

#15 #define  Icon User is online

  • Duke of Err
  • member icon

Reputation: 1345
  • View blog
  • Posts: 4,633
  • Joined: 19-February 09

Re: Trouble with overloaded '==' operator

Posted 10 March 2013 - 11:33 PM

I get somewhere if I create a temporary variable for the searchValue, it seems something to do with const and the reference.

      V sv = searchValue;
      if ( operator==(sv, *(list[ mid ])) )
        return mid;   // found value.


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2