我有下面的类层次结构。基本上,我想在类 Foo 和 CComplexMat 之间建立一个“有一个”关系,即类 Foo“有一个”CComplexMat。
据我所知,private
和 protected
不能从定义它们的类的外部访问类的成员。
但是,有两种可能允许其他类访问此类成员。
第一个是使用 friend
类。我可以添加一行 friend class Foo<T>;
在 class CComplexMat<T>
的声明中, 以便
Foo<T>
可以访问 protected
和 private
class CComplexMat<T>
的成员.
第二种可能是使用 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;
...
};
最佳答案
继承只能用于“is-a”关系。在我看来它像 CComplexMat<T>
有两个CMatrix<T>
成员,但事实并非如此,它"is" CMatrix<T>
.类似处理Foo
和 CComplexMat<T>
.
所以继承几乎肯定不是正确的解决方案。剩下的是:
- 使用
friend
允许在密切相关的类之间进行访问。 - 使用公共(public)访问器方法允许类的用户以有限的方式“访问”私有(private)成员。
例如,CComplexMat<T>
实部和虚部可能应该有私有(private)成员,但也应该有一些访问器,如:
public:
const CMatrix<T>& realPart() const;
CMatrix<T>& realPart();
const CMatrix<T>& imagPart() const;
CMatrix<T>& imagPart();
关于c++ - 友元与继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4821268/