I am trying to implement a Priority Queue using a Vector template in C++. I am most comfortable with Java and want to mimic the idea of an Interface, where all objects that can use the Priority Queue are required to implement certain methods.
I know that C++ does not support Interfaces, however, someone suggested that by tapping into Multiple Inheritance this could be achieved by creating an Abstract Class and requiring some virtual functions.
I would like all objects that can use the Priority Queue to implement:
public:
int compareTo(Comparable &obj);
Here is a C++ Abstract Class that achieves this: Comparable.h
class Comparable {
public:
Comparable();
~Comparable();
virtual int compareTo(Comparable &obj) = 0;
};
This works great, no errors are formed from supplying the Abstract Class to the Vector template:
vector<Comparable> *mElements = new vector<Comparable>(); // no error
It is not until I try to use polymorphism in a class that inherits from the Comparable class that I run into an issue. Because the Method signature receives a Comparable&, I am having trouble accessing the members of the class that extends Comparable:
int Event::compareTo(Comparable& obj) {
// Min-Heap - time of currentObject is less than e.mTime
Event e = (Event) obj; // Doesn't work - No C-style cast (can I make one and how?)
// if I trying obj.mTime, this won't work because it is not a member of the Comparable class
if (mTime < e.mTime) return Delta::NEGATIVE_CHANGE;
if (mTime > e.mTime) return Delta::POSITIVE_CHANGE;
return return Delta::NO_CHANGE;
}
All I need to do is compare the time in this example, but I would like to design the class so that clients only have to inherit from the Comparable class and implement the one method for use of the priority queue.
Thanks for any help in advanced!
Aucun commentaire:
Enregistrer un commentaire