Inheriting from an instance of a template class
I have two classes as follows in a header file
template<size_t N>
class Parent{
protected:
char array[N];
size_t i;
public:
virtual void operator()(int i);
};
template<size_t N>
void 开发者_如何转开发Parent<N>::operator()(int i){
this->i = i;
}
class Child: public Parent<16>{
public:
virtual void operator()();
};
Child has operator()() defined elsewhere in a cpp file. Whenever I include this header file from another cpp file I can access operator()() but operator()(int) is not even defined. Why is this? I thought since I inherit from a specific instance of Parent, all the methods of it should be instanced as well and available.
Apart from the errors in your code, this is an example of hiding: Your derived class declares a function of the same name but with different signature as a base class. Thus the base function is hidden:
class A { virtual void foo(); };
class B : public A { virtual void foo(int); /* hides A::foo() ! */ };
Inheritance only affects functions that have the same signature (with some mild exceptions).
Your base class function is declared as void Parent<N>::operator()(int)
, while in your derived class you declare void Child::operator()()
.
In C++11 you can explicitly say virtual void foo(int) override
to trigger a compiler error if the function isn't overriding anything.
If you intentionally want to define a new function with the same name as an existing one but with different signature, and not overriding the base function, then you can make the base function visible with a using
directive:
class C : public A
{
using A::foo();
void foo(int);
}; // now have both C::foo(int) and C::foo()
Because the Parent's operator() hides the Child's operator() (they have different signatures). How come you are not getting warnings when you compile your code?
This is how it should be :
class Child: public Parent<16>{
public:
using Parent<16>::operator();
virtual void operator()();
};
精彩评论