C++ Polymorphism模板类:调用基类方法而不是派生类

Kha*_*Tea 2 c++ oop templates

我不知道为什么C++编译器运行基类方法(类排序的排序方法)而不是派生类方法(类SelectionSort的排序方法).

template <typename T>
class Sorting {
public:
    virtual void sort(T* data, int size, Comparator<T> comparator) const {
    };
};

template <typename T>
class SelectionSort : public Sorting<T> {
public:
    void sort(T* data, int size, Comparator<T> comparator) {
        // my selection sort code
    };
};

template <typename T>
void Array<T>::sort(Sorting<T> algorithm, Comparator<T> comparator) {
    algorithm.sort(data, size, comparator); /// Problem is here !
};

int main() {
    int nums[] = { 2, 1, 3 };
    Array<int> arr(nums, 3);
    SelectionSort<int> sorting = SelectionSort<int>();
    AscendingComparator<int> comparator = AscendingComparator<int>();
    arr.sort(sorting, comparator);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 6

您的具体问题是对象切片.你看起来像是来自Java,这可能会起作用 - 但是在C++中,当你复制它时,你会失去对象的所有重要部分.您需要做的是通过引用获取您的接口:

template <typename T>
void Array<T>::sort(Sorting<T>& algorithm, Comparator<T>& comparator) {
                              ^                         ^
    algorithm.sort(data, size, comparator);
};
Run Code Online (Sandbox Code Playgroud)

同样在内Sorting::sort()- 需要Comparator参考.请注意,如果你制作了Sorting抽象基类,那就是:

template <typename T>
class Sorting {
public:
    virtual void sort(T* , int , Comparator<T> ) const = 0;
    //                                                ^^^^
};
Run Code Online (Sandbox Code Playgroud)

编译器会为您捕获此错误,因为您无法创建类型的对象Sorting<T>- 您的代码将需要它.

请注意,正如Angew指出的那样,你的SelectionSort类实际上没有覆盖,Sorting<T>::sort因为它缺少const修饰符.如果sort()在基类中是纯虚拟的,编译器也会指出这个错误.

您的代码中还有一些其他Java内容:

SelectionSort<int> sorting = SelectionSort<int>();
AscendingComparator<int> comparator = AscendingComparator<int>();
Run Code Online (Sandbox Code Playgroud)

应该只是:

SelectionSort<int> sorting;
AscendingComparator<int> comparator;
Run Code Online (Sandbox Code Playgroud)