I started learning c++ not a long time ago, and I've got a tricky problem...
I have to write a static library, which is able to sort ANY type arrays of objects, and I don't really know how to do it... What to write in the header of function?
#ifndef SORTER
#define SORTER
class sorter
{
public:
static array* bubblesort(array*,int size_t);
};
#endif
This solution is the best that I could do, but of course it doesnt work...
What I would like to sort:
int main()
{
const unsigned maxEquipment=7;
Equipment* equipments[maxEquipment];
equipments[0]=new Equipment(1,200);
equipments[1]=new Printer(2,12000,12000);
equipments[2]=new Display(3,2000,6);
equipments[3]=new Printer(4,312000,51000); ...........
NOTE: I cant use any kind of sorter function from standard lirary!
Any ideas what to do?
You can accomplish this by providing a common base class that has a pure virtual function. This will allow you to enforce the requirements for sorting the array without having to worry about dealing with multiple object types.
For example if you wanted to sort on an int
value. You would add a pure virtual to retrieve the value. The forces all derived classes to implement the member function and return a value.
class SortBase
{
public:
virtual ~SortBase() {} // <-- required for polymorphism
virtual int getValue() const = 0;
};
One you have your base class you use it to provide a requirement for your bubble sort routine that says you must inherit from this class if you want to use me.
class sorter
{
public:
static const SortBase* bubblesort(const SortBase*,int size_t);
};
Then you inherit from the SortBase
class and provide an implementation for getValue
class Display : public SortBase
{
public:
Display(int value) : value_(value) {}
virtual int getValue()
{
return value_;
}
private:
int value_;
};
Your example main
would then look something like below
int main()
{
const unsigned maxEquipment=4;
SortBase* equipments[maxEquipment];
equipments[0]=new Equipment(1,200);
equipments[1]=new Printer(2,12000,12000);
equipments[2]=new Display(3,2000,6);
equipments[3]=new Printer(4,312000,51000);
sorter::bubblesort(equipments, maxEquipment);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.