converting 'int' to user-created class

Having a small problem with a function I'm trying to run.

Employees *ptr = tree.empSearch(srchNum);
srchNum is an int initialized to equal 0. The function empSearch is supposed to accept an employee ID number, search my binary tree, and return the employees name as well as the corresponding ID number (which would be the same as the one entered for srchNum).

Here are my function and declaration

T *empSearch(T);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class T>
T *BSTtemplate<T>::empSearch(T item)
{
	TreeNode *nodePtr = root;

	while (nodePtr)
	{
		if (nodePtr->value == item)
			return &nodePtr-> value;
		else if (item < nodePtr->value)
			nodePtr = nodePtr->left;
		else
			nodePtr = nodePtr->right;
		
	}
	return NULL;
}


I know this works, as I've seen it execute in an example program, and I'm trying to follow the same logic, but for some reason Employees *ptr = tree.empSearch(srchNum); keeps throwing me an error for srchNum, saying it couldn't be converted from 'int' to my 'Employees' class. I've tried to look up how to convert it, but I haven't found anything.

Does anyone know of a way?
That's happening because the empSearch() takes an Employees object as its argument, not an integer. T=Employees in your instantiation right?

This search function requires more than just that idNums match up. The line nodePtr->value == item is testing for whatever the == operator was overloaded to do in the Employees class.

Problem with trying to cobble together a solution from pieces found on the internet is sometimes you aren't sure what something does, huh?
Last edited on
Okay, I understand that empSearch() takes an Employees object as an arguement, and so obviously I can't use an int as the arguement. I know that, but I have seen it done in a working program, which I have and I'm trying to follow the logic to make my own work.

I've tried instantiating an object of my BSTtemplate class to accept an int, but I realized that wouldn't work, because an int can't be used to instantiate an Employees class object.

So obviously this isn't working the way I've been trying to do it. I'm going to step back and try a different method. I can get the information into the tree, it's doing this search that is the problem.
You CAN make it so that an integer will convert to an Employees object.

Write a constructor which takes an int value only:
1
2
3
4
5
Employees(int ID)	//Constructor
	{
		id = ID;
		empName = "Bob";// default name
	}

The compiler should use this ctor to create an Employees object from the integer value given to empSearch(). ie. It will use this ctor to "cast" an integer to an Employees object.

I just checked your definition of operator== (in the other thread I helped you with) and all it does is compare values of idNum, so the search should work.
Last edited on
Topic archived. No new replies allowed.