[英]C++ Polymorphism template class : calling base class method instead of derived class
我不知道为什么C ++编译器运行基类方法( Sorting类的排序方法)而不是派生类方法( 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;
}
您的特定问题是对象切片 。 您看起来就像来自Java,这在Java中就可以工作-但是在C ++中,复制对象时会丢失该对象的所有重要部分。 您需要做的是通过引用获取接口:
template <typename T>
void Array<T>::sort(Sorting<T>& algorithm, Comparator<T>& comparator) {
^ ^
algorithm.sort(data, size, comparator);
};
同样在Sorting::sort()
-需要通过引用获取Comparator
。 请注意,您是否进行了Sorting
和抽象基类,即具有:
template <typename T>
class Sorting {
public:
virtual void sort(T* , int , Comparator<T> ) const = 0;
// ^^^^
};
编译器将为您捕获此错误,因为您无法创建您的代码将需要的Sorting<T>
类型的对象。
还要注意,正如Angew指出的那样,您的SelectionSort
类实际上没有覆盖Sorting<T>::sort
因为它缺少const
修饰符。 如果sort()
在基类中是纯虚拟的,则编译器也会向您指出此错误。
您的代码中还有其他一些Java内容:
SelectionSort<int> sorting = SelectionSort<int>();
AscendingComparator<int> comparator = AscendingComparator<int>();
应该只是:
SelectionSort<int> sorting;
AscendingComparator<int> comparator;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.