c++ - 友元与继承

标签 c++ inheritance friend protected access-control

我有下面的类层次结构。基本上,我想在类 Foo 和 CComplexMat 之间建立一个“有一个”关系,即类 Foo“有一个”CComplexMat。 据我所知,privateprotected不能从定义它们的类的外部访问类的成员。

但是,有两种可能允许其他类访问此类成员。 第一个是使用 friend类。我可以添加一行 friend class Foo<T>;class CComplexMat<T> 的声明中, 以便 Foo<T>可以访问 protectedprivate class CComplexMat<T>的成员.

第二种可能是使用 inheritance ,这是我在示例中选择的解决方案。在这种情况下,我正在考虑 public继承所以 两者 publicprotected class CComplexMat<T>的成员在类里面可以访问 Foo<T> .但是,显示以下错误:

error: ‘CMatrix<float>* CComplexMatrix<float>::m_pReal’ is protected

error: within this context

  1. 我想知道是否有人可以阐明这个错误?
  2. “友元”或“继承”在哪些情况下更合适?
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> .类似处理FooCComplexMat<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/

相关文章:

c++ - mysql C++ 从所有列中选择所有行

c# - 继承和 JSON 转换

c++ - gtkmm 应用程序内存使用量不断增加

c++ - 嵌套循环 : permuting an n-dimensional array represented by a vector

c++ - 从模板类继承,使用派生类中定义的类型

java - 如何通过多级继承调用错误的override方法?

C++友元函数不能访问私有(private)成员

c++ - C++派生类访问基类的好友运算符

C++:成员不可访问 - 使用友元函数允许一个类修改另一个类的成员数据

c# - 如何在 C# 中固定指向托管对象的指针?