could anyone please help to resolve this (the problem is persistent under both GCC and VC++).
template <class T> class A{
protected:
T a;
public:
A(int aa=0){a=aa;}
virtual ~A(){}
virtual void plus(A const *AA){a开发者_开发知识库=a+AA.a;}
};
class B:public A<int>{
public:
B(int bb=0):A<int>(bb){}
virtual ~B(){}
void plus(A<int> const *AA){a=a+AA->a;} //<--PROBLEM: I can access a but not AA->A?
};
This is to be expected.
An instance of B has no right poking around in the internals of an arbitrary A; it has a right only to access the A part of (other) Bs. That's what the protected keyword means.
This is not a problem with compilers but standard conformant behaviour. You can access protected members of a base class only through this
(implicitly or explicitely).
This should look like:
class B:public A<int>{
public:
B(int bb=0):A<int>(bb){}
virtual ~B(){}
void plus(A<int> const *AA){this->A::plus(AA);}
};
No need to reimplement the plus function in the derived class if it's doing the same.
"UncleBens" has already answered your main question, but some details...
First:
virtual void plus(A const *AA){a=a+AA.a;}
Since AA
is a pointer you can't do AA.a
... ;-)
Second, be aware that member pointers do not generally honor accessibility. Using just implicit conversions you can gain access to a base class' protected stuff. Member pointers are to accessibility about the same as what goto
is to flow control.
Cheers & hth.,
– Alf
精彩评论