aka*_*101 2 c++ polymorphism inheritance templates overriding
我试图覆盖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"
}
Run Code Online (Sandbox Code Playgroud)
请注意,对于参数类型const T&
,其自身const
是合格的T
,则当T
指针为时int *
,该参数const
应int* const
仅对指针本身(即)而不是指针对象(即const int*
)进行限定。
正确的类型应该是
void doSomething(int* const & t)
Run Code Online (Sandbox Code Playgroud)
顺便说一句:您可以使用关键字override
来确认该virtual
功能是否被正确覆盖。
BTW2:更改为风格const T&
,以T const&
可能使之更加清晰。
归档时间: |
|
查看次数: |
40 次 |
最近记录: |