I do this excercise:
Implement a sort function that takes a vector of pointers to an interface class, Comparable,
that defines a method, compare(Comparable& other), and returns 0 if the objects are the
same, 1 if the object is greater than other, and -1 if the object is less than other. Create a class
that implements this interface, create several instances, and sort them. If you're looking for
some inspiration for what to create—try a HighScoreElement class that has a name and a
score, and sorts so that the top scores are first, but if two scores are the same, they are sorted
next by name.
I got this error:
E:\Programming\C++\sortFuntionInheritance\main.cpp||In function 'int main()':|
E:\Programming\C++\sortFuntionInheritance\main.cpp|13|error: cannot allocate an object of abstract type 'highScore'|
E:\Programming\C++\sortFuntionInheritance\comparable.h|9|note: because the following virtual functions are pure within 'highScore':|
E:\Programming\C++\sortFuntionInheritance\comparable.h|7|note: virtual int Comparable::compare(Comparable*)|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|
I dont know why compiler said highScore has pure virtual function, plz help correct my program. Thank very much.
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include "comparable.h"
using namespace std;
int main()
{
char ch = 'y';
highScore* p_score = NULL;
vector<Comparable*> v_score;
while (ch == 'y')
{
p_score = new highScore;
cout << "Input name: "; cin >> p_score->name;
cout << "Input score: "; cin >> p_score->score;
v_score.push_back(p_score);
cout << "Do you want to continue? y/n"; cin >> ch;
}
sort(v_score);
return 0;
}
|
comparable.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <string>
#include <vector>
class Comparable
{
public:
virtual int compare(const Comparable& other) = 0;
};
class highScore:public Comparable
{
public:
virtual int compare(const Comparable& other);
int score;
std::string name;
};
void sort(std::vector<Comparable*>);
|
comparable.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include "comparable.h"
int highScore::compare(const Comparable& other)
{
if (this->score == other.score || this->name == other.name)
return 0;
if (this->score > other.score)
return 1;
else
return -1;
return this->name.compare(other.name);
}
void sort(std::vector<Comparable*> v_score)
{
Comparable* temp = NULL;
//sorting starts by finding the biggest element and changing its pointer with the first element of the list, then finds
//the second biggest element and changes it pointer with the second element and go on until reach the end of the list
for (int i = 0, size = v_score.size(); i < size-1; i++)
for (int j = i+1; j < size; j++)
{
if (v_score[i]->compare(v_score[j]) < 0)
{
temp = v_score[i];
v_score[i] = v_score[j];
v_score[j] = temp;
}
}
}
|