开发者

C++ keeping access to protected member (of the function argument) when specializing base template class

开发者 https://www.devze.com 2023-01-19 15:54 出处:网络
could anyone please help to resolve this (the problem is persistent under both GCC and VC++). template <class T> class A{

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

0

精彩评论

暂无评论...
验证码 换一张
取 消