I have a class hierarchy below. Basically, I would like to establish a "has-a" relationship between the Foo and CComplexMat classes, i.e. Class Foo "has-a" CComplexMat. From what I know, privateand the protectedmembers of the class can not be accessed from outside the class in which they are defined.
However, there are two possibilities to allow other classes access to such members. The first is to use classes friend. I could add a line friend class Foo<T>;in the advertisement class CComplexMat<T>, so that
Foo<T>can access protectedand privatemembers class CComplexMat<T>.
A second possibility would be to use inheritance, which is the solution I chose in the example. In this case, I consider the inheritance publicso that both public, and protectedthe members class CComplexMat<T>are available in the classroom Foo<T>. However, the following error is displayed:
error: ‘CMatrix<float>* CComplexMatrix<float>::m_pReal’ is protected
error: within this context
- I was wondering if anyone can shed some light on the mistake?
- In what situations are “friendships” or “inheritance” more convenient?
template <class T>
class CMatrix{
public:
...
CMatrix<T> & operator = (const CMatrix<T> &);
T & operator()(int, int, int);
T operator()(int, int, int) const;
...
private:
T *** pData;
int rows, cols, ch;
};
template <class T>
class CComplexMat: public CMatrix<T>{
public:
...
protected:
CMatrix<T> *pReal;
CMatrix<T> *pImag;
};
template <class T>
class Foo: public CComplexMat<T>{
public:
...
void doSomething(){
...
CMatrix<T>*pTmp = pComplex->pReal;
...
}
...
private:
CComplexMat<T> * pComplex;
...
};
source
share