声明一个派生类是朋友访问基类的私有成员

时间:2018-03-15 03:32:54

标签: c++ templates inheritance friend

我有以下继承结构:

template<unsigned int t>
class Base {
protected:
    int a;
};

template<unsigned int t>
class Derived1 : public Base {

};

template<unsigned int t>
class Derived2 : public Base {

};

我想要的是让Derived1构造函数将Derived2对象作为参数,然后访问受保护的成员&#39; a&#39;在基类中。

我已将以下行添加到基类:

template<unsigned int u> friend class Derived2;

所以看起来如下:

template<unsigned int t>
class Base {
protected:
    int a;

template<unsigned int u> friend class Derived2;
};

当我编译它时,我得到错误C2248:&#34;无法访问在类Base#34中声明的受保护成员;

1 个答案:

答案 0 :(得分:1)

如果你想从Derived1构造函数访问受保护的成员,那么你需要成为Derived1而不是Derived2的朋友。

template<unsigned int t>
class Base {
protected:
    int a;

    template<unsigned int u> friend class Derived1; // here
};

template <unsigned int>
class Derived2;

template<unsigned int t>
class Derived1 : public Base<t> {
public:
    Derived1(Derived2<t>& d2) {
        cout << d2.a << endl;
    }
};

template<unsigned int t>
class Derived2 : public Base<t> {

};

int main() {
    Derived2<1> d2;
    Derived1<1> d1(d2);

    return 0;
}