C++重写虚拟模板化方法
C++ overriding virtual templated method
我正在尝试覆盖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&
可能会使其更清晰。
住
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 如何强制从重写方法调用重写的方法基方法?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 在 C++ 中使用模板方法重写类方法
- 检查子类是否执行了方法重写
- C++方法重写和重载(编译器级别)
- 用模板方法重写虚拟方法
- 方法重写(没有虚拟方法或指针)是否被认为是多态性的一部分
- C++ - 方法重写未按预期表示
- 使用两种方法重写<<运算符
- C++阻止方法重写
- C++方法重写
- c++在具体类中强制方法重写
- 方法重载和方法重写的性能问题
- C++中的方法重写是否总是在派生类的标头中完成?
- 是否有更好的方法重写此代码片段
- 为什么静态方法重写基类非静态方法
- 方法重写