C++重写虚拟模板化方法

C++ overriding virtual templated method

本文关键字:方法 重写 虚拟 C++      更新时间:2023-10-16

我正在尝试覆盖C++中的虚拟函数。在我重写函数后,它实际上并没有覆盖它,从而使类抽象。 下面的代码将使您很好地理解问题。

正如你在下面看到的,代码适用于非指针模板,如 int,但使用 int 指针失败。

我想也许是因为引用指针的问题,我在 Derived2 的实现中取出了 &,但这并没有解决它。

template<class T>
class Base {
virtual void doSomething(const T& t) = 0;
};
class Derived1: public Base<int>{
void doSomething(const int& t) {
} // works perfectly
};
class Derived2: public Base<int*>{ 
void doSomething(const int*& t) { 
}
// apparently parent class function doSomething is still unimplemented, making Derived2 abstract???
};
int main(){
Derived1 d1;
Derived2 d2; // does not compile, "variable type 'Derived2' is an abstract class"
}

注意,对于参数类型const T&const限定在T本身,那么当T是像int *这样的指针时,const应该限定在指针本身(即int* const),而不是尖(即const int*)。

正确的类型应该是

void doSomething(int* const & t)

顺便说一句:您可以使用关键字override来确认是否正确覆盖了virtual函数。

BTW2:将const T&的样式更改为T const&可能会使其更清晰。