受保护成员在派生类中"not declared in this scope"

Protected member is "not declared in this scope" in derived class

本文关键字:not declared this scope in 成员 派生 受保护      更新时间:2023-10-16
#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类中不可见吗?

要解决此问题,您需要指定 Base<T>::data_.clear()this->data_.clear() 。至于为什么会发生这种情况,请参阅此处。

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

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

当编译器查找派生类定义时,它不知道继承了哪个Base<T>(因为T未知(。此外,data_不是任何template参数或全局可见变量。因此,编译器对此表示不满。