问题
I have a template base class.Lets say.
template<class KeyF>
class Base
{
private:
int member1;
char member2;
....
};
I derived another class from above class.
template<class KeyF>
class Derived : public Base<KeyF>
{
public:
void func1() {
<accessing member1/member2>
}
....
};
Above code doesn't compile in gcc. saying that member1 is not a member of Derived. But it is already derived from a Base Class, then why can't it access its member?
回答1:
Members in Base
are private
. You cannot access private members
of class, outside of this class (except friend
). Make them protected
, or make protected getters
.
回答2:
Did you try protected? Been a bit since I was deep into C++...
回答3:
You need to prefix base member names with this->
or Base<KeyF>::
, or add a using
declaration to the class to unhide them. Their names are dependent names, and they are hidden.
来源:https://stackoverflow.com/questions/12514673/cant-access-members-of-a-template-base-class-within-a-derived-template-class