I have an assignment where I have to construct a nonmember function which calls a member function inside it.
The issue lies inside the testSuccesfulSearch function, where I have to call the object "obj" to call the member linearsearch (which is a member function inside class)
the error states: the object has type qualifers that are not compatible with the member function
#include <iostream>
#include <ctime>
usingnamespace std;
class Myclass
{
private:
int *ptr; //pointer to 1D dynamic array
int size;
public:
Myclass(int arraySize) //overload constructor
{
size = arraySize;
ptr = newint[size];
cout << "Enter data for an array size: " << size << endl;
for (int i = 0; i < size; i++)
{
cin >> ptr[i];
}
cout << endl;
}
int linearSearch(int searchItem) const; //linear search
~Myclass()
{
delete[] ptr;
cout << "Memory reallocated!" << endl;
}
};
int Myclass::linearSearch(int searchItem) const
{
srand(time(0));
int item = searchItem;
for (int i = 0; i < size; i++)
{
if (ptr[i] == item)
{
return i;
break;
}
}
return -1;
}
double testSuccesfulSearch(const Myclass &obj, longint runCount);
int main()
{
Myclass B(10);
float average;
average = testSuccesfulSearch(B, 10000);
system("PAUSE");
return 0;
}
double testSuccesfulSearch(const Myclass &obj, longint runCount)
{
obj.linearSearch(runCount);
}
In the function prototype for testSuccessfulSearch, you've stated to the compiler that obj is const. Therefore, the only functions that may be invoked on obj are those that are marked const.
No, just make the linearSearch function const by adding const in those two places I showed in my last post. What that does is tell the compiler "This method promises not to change the object that invokes it."
Ah interesting, I've never seen the const used like that before. Thank you, the program works fine now, however there is one slight issue left:
My program is intended to take the runcount, initialize it in the linearsearch function, and go through a loop of runcount times, creating a random number each time and searching for that random number in the array.
So for example: if my array consists of 10 integers and my run count is 10000, the loop will initialize 10000 times, creating a random number each time and searching for that said number in the array of 10 integers. If the number is found, I have to increment a counter, and return the counter to find the average number of times that number appeared