Dan*_*iel 5 c++ oop polymorphism virtual-functions c++14
我有一个基类,其中有一个纯虚函数,并且使用这个函数,我想在其他派生类中覆盖它(如果可能,在某些派生类中使用不同数量的参数)。
所以在 MergeSort 子类中,我有 MSort 方法,它需要不同数量的参数,因为它是递归完成的。
因此,目前使用这些参数使用此函数时,我收到此错误“MergeSort:”无法实例化抽象类。但是,如果我覆盖基类中的 Sort 方法工作正常,但我不需要一个参数。
我还尝试用不同数量的参数声明另一个虚函数,并在 MergeSort 类中定义它,我得到了同样的结果。
我还想澄清一下,对于不同的算法(冒泡排序、插入排序等),我还有其他子类,它们的实现类似于 MergeSort(一个构造函数和一个排序函数),但排序函数具有相同的参数数量(只有一个用于图形界面)就像在上面的基类中一样。
那么是否有可能有一个具有不同数量参数的覆盖方法?或者我上面所说的任何其他解决方案?
// BASE CLASS
// Forward declaration
class Interface;
/**
* Base class from which the sorting algorithms classes will inherit (Polymorphic class)
* The base class will allow us to create a sequence with n elements
*/
class SortingAlgorithms
{
protected:
std::vector<sf::RectangleShape> sequence; // vector which will contain a randomized sequence
std::vector<sf::RectangleShape> sequenceCpy; // a copy of sequence used for interaction features
sf::RenderWindow& window; // initializes the window
int minimum, maximum; // the range in which the elements will be randomized
int elements; // the number of elements which will be initialized
public:
SortingAlgorithms();
/** SortingAlgorithms() - class constructor which initializes the sequence
* @param min - the minimum value for randomizing
* @param max - the maximum value for randomizing
* @param els - the number of elements to generate
* @param win - since the window will be initialized only once (singleton pattern);
* it will be needed to pass on this object to almost every function that has
graphics features
*/
SortingAlgorithms(int min, int max, int els, sf::RenderWindow& win);
// A pure virtual function for overriding and param init which is what I described about win param from SortingAlgorithms constructor
virtual void Sort(std::unique_ptr<Interface>& init) = 0;
};
class MergeSort : public SortingAlgorithms
{
public:
MergeSort(int min, int max, int els, sf::RenderWindow& win);
void Merge(std::unique_ptr<Interface>& init, int first, int mid, int last);
void MSort(std::unique_ptr<Interface>& init, int first, int last);
};
Run Code Online (Sandbox Code Playgroud)
如评论中所述,您必须对所有覆盖使用相同的签名。为此,您可以使用以下方法:使用覆盖函数作为一种入口点,在其中调用执行排序的实际函数(可能是私有函数)。举例说明该方法:
class SortingAlgo
{
public:
virtual void sort(int arr[], int n) = 0;
};
class BubbleSort: public SortingAlgo
{
public:
void sort(int arr[], int n){
this->bubble_sort(arr, n);
}
private:
void bubble_sort(int arr[], int n){
//implemetation
}
};
class MergeSort: public SortingAlgo
{
public:
void sort(int arr[], int n){
this->mergeSort(arr, 0, n - 1);
}
private:
void mergeSort(int arr[], int l, int r){
//recursive implemetation
}
void merge(int arr[], int l, int m, int r){
//implemenation
}
};
Run Code Online (Sandbox Code Playgroud)