So my question has to do with the " virtual int compare " method. im trying to make superclass that would allow subclasses to be sorta based on their values.
the error im getting is "no matching function call to comparable::compare( comparable& other )". when i remove the parameter of " comparable& other " , the problem seems to go away. to get to the point, am i just implementing this wrong? also any explanation of whats going on here would be nice. thank you
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
class comparable
{
public:
comparable();
virtualint compare( comparable& other ) = 0;
int getValue();
virtual ~comparable();
private:
comparable( const comparable& other );
protected:
int value;
};
class highScore : public comparable
{
public:
virtualint compare( comparable& other );
highScore();
highScore( int score , string name );
virtual ~highScore();
private:
int* Score;
string* Name;
};
comparable::comparable()
{
}
comparable::~comparable()
{
}
int comparable::getValue()
{
return value;
}
highScore::highScore()
{
Score = newint( 0 );
Name = new string( "blank" );
value = *Score;
}
highScore::highScore( int score, string name )
{
Score = newint( score );
Name = new string( name );
value = *Score;
}
highScore::~highScore()
{
delete Score;
delete Name;
}
int highScore::compare( comparable& other )
{
int other_val = other.getValue();
if ( *Score == other_val )
return 0;
if ( *Score > other_val )
return 1;
elsereturn -1;
return 0;
}
int main()
{
vector<comparable*> comparables;
comparables.push_back( new highScore( 1234, "test" ) );
comparables.push_back( new highScore( 1235, "test" ) );
vector<comparable*>::iterator itr1 = comparables.begin();
vector<comparable*>::iterator itr2 = comparables.begin();
*itr2++;
cout << (*itr1)->compare( (*itr2) );
return 0;
}
EDIT: some of the things ive done here might seem strange, thats because ive been trying everything i can think of to make this problem go away
the error im getting is "no matching function call to comparable::compare( comparable& other )".
Your vector 'comparables' contains comparable* pointers, so you're trying to pass a pointer to a function that expects a comparable& reference.
Calling compare like this will work
cout << (*itr1)->compare( *(*itr2) ); // or even just **itr2
But it might make sense to alter the compare method to take a pointer if you plan to work mainly with pointers.
Andy
PS You do say that you've done some strange thing; so I assume you know that neither int nor std::string members are usually allocated using new, and that your code is just an exercise in pointer management.