【问题标题】:Protected member is "not declared in this scope" in derived class [duplicate]派生类中的受保护成员“未在此范围内声明”[重复]
【发布时间】:2012-08-15 11:16:07
【问题描述】:
#include <vector>
#include <iostream>

template <class T>
class Base
{
protected:
    std::vector<T> data_;
};

template <class T>
class Derived : public Base<T>
{
public:
    void clear()
    {
        data_.clear();
    }
};

int main(int argc, char *argv[])
{
    Derived<int> derived;
    derived.clear();
    return 0;
}

我无法编译这个程序。我明白了:

main.cpp:22: error: 'data_' was not declared in this scope

请您解释一下为什么data_Derived 类中不可见?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    要解决此问题,您需要指定Base&lt;T&gt;::data_.clear()this-&gt;data_.clear()。至于为什么会这样,请看here

    【讨论】:

    • 谢谢!它适用于 Base::data_.clear() 或 this->data_.clear()!
    • Derived::data_.clear() 也可以。
    • 对我来说这是编译器中的一个错误。它应该研究基类。谁在乎名字是否依赖。
    • @KirillKobelev,我想说没有this-&gt; 是编译器限制而不是错误。想象一下,基类专门用于int,即Base&lt;int&gt;,而该类没有data_。现在编译器不知道当前的Derived&lt;T&gt; 是否专门用于int。如果编译器假定this-&gt; 那么它将成为一个真正的错误。
    • @KirillKobelev:MSVC 编译器将接受data_.clear();,但这是因为它没有实现两阶段名称查找。
    【解决方案2】:

    在模板的情况下,编译器无法确定成员是否真的来自基类。所以使用this指针,它应该可以工作:

    void clear()
    {
       this->data_.clear();
    }
    

    当编译器查看 Derived 类定义时,它不知道哪个Base&lt;T&gt; 被继承(因为T 是未知的)。此外,data_ 不是任何 template 参数或全局可见变量。因此编译器会抱怨它。

    【讨论】:

    • 谢谢!您的建议有效!
    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2011-09-14
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2018-11-27
    相关资源
    最近更新 更多