【问题标题】:C++ derived template class: Access protected member of an instanceC++ 派生模板类:访问实例的受保护成员
【发布时间】:2013-09-17 05:51:04
【问题描述】:

我有一个模板基类和一个派生模板类。派生的方法有一个重载方法,其参数包含对基类相同类型对象的引用。如果这些不是模板类,我会让派生类成为基类的朋友,这样我就可以在这种情况下访问基类的受保护成员,但是我该如何使用模板呢?

template <typename T>
class base
{
    // If this wasn't a template class, I would have done this:
    // friend class derived;

public:
    base(T val)
        : val_(val)
    {
    }

    virtual void assign(const base<T>& other)
    {
        val_ = other.val_;
    }

protected:
    T val_;
};

template <typename T>
class derived : public base<T>
{
public:
    derived(T val)
        : base<T>(val)
    {
    }

    virtual void assign(const base<T>& other)
    {
        this->val_ = other.val_; // error: ‘int base<int>::val_’ is protected
    }
};

int main()
{
    derived<int> a(5);
    derived<int> b(6);
    b.assign(a);
    return 0;
}

【问题讨论】:

  • 为什么不简单地base&lt;T&gt;::assign(other);?为什么derived负责管理base的状态?无论如何,如果你真的想使用friend,你可以:template &lt;typename T&gt; class derived; template &lt;typename T&gt; class base { friend class derived&lt;T&gt;; };
  • cmbasnett:不是,实际上我在发布并尝试了那里的建议之前已经阅读了那个特定的问题,但这种情况是不同的。我正在尝试访问另一个实例的受保护成员。
  • Igor,感谢模板类的前向声明并将其声明为朋友似乎可以解决问题。

标签: c++ templates friend derived


【解决方案1】:

为什么有virtual?在您的示例中,derived::assign()base::assign() 的作用相同。

class base
{
    ...
    public:
    ...
    void assign(const base<T>& other)
    ...
}
derived<int> b(6);
b.assign(a); //calls base<int>::assign(..)

如果derived 应该在assign(..) 中做更多工作,请使用 base&lt;T&gt;::assign(other);as proposed by Igor Tandetnik。无需使用friend

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2012-05-26
    • 2011-03-10
    • 2016-04-07
    • 2019-09-28
    • 2023-03-18
    相关资源
    最近更新 更多