【问题标题】:Declaring one derived class a friend to access private member of base class将一个派生类声明为朋友以访问基类的私有成员
【发布时间】:2018-08-23 18:33:57
【问题描述】:

我有以下继承结构:

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 对象作为参数,然后访问 Base 类中的受保护成员 'a'。

我在基类中添加了以下行:

template<unsigned int u> friend class Derived2;

所以它看起来如下:

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

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

编译时出现错误 C2248:“无法访问 Base 类中声明的受保护成员”

【问题讨论】:

    标签: c++ templates inheritance friend


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 2015-11-24
      • 2021-08-16
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2014-06-18
      相关资源
      最近更新 更多