【发布时间】:2011-06-16 19:34:35
【问题描述】:
我有下面的类层次结构。基本上,我想在 Foo 和 CComplexMat 类之间建立“has-a”关系,即 Foo 类“has-a”CComplexMat。
据我所知,类的private 和protected 成员无法从定义它们的类外部访问。
但是,允许其他类访问此类成员有两种可能性。
第一个是使用friend 类。我可以在class CComplexMat<T> 的声明中添加一行friend class Foo<T>;,这样
Foo<T> 可以访问class CComplexMat<T> 的protected 和private 成员。
第二种可能是使用inheritance,这是我在示例中选择的解决方案。在这种情况下,我正在考虑使用public 继承,以便
public 和 protected 的成员 class CComplexMat<T> 都可以在类 Foo<T> 中访问。但是,显示以下错误:
error: ‘CMatrix<float>* CComplexMatrix<float>::m_pReal’ is protected
error: within this context
- 我想知道是否有人可以阐明这个错误?
- 在哪些情况下“友情”或“遗产”更合适?
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; // error here.
...
}
...
private:
CComplexMat<T> * pComplex;
...
};
【问题讨论】:
标签: c++ inheritance friend protected access-control