受保护成员在派生类中"not declared in this scope"
Protected member is "not declared in this scope" in derived class
#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
参数或全局可见变量。因此,编译器对此表示不满。
相关文章:
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 如何解决"cout was not declared in this scope"错误?
- 为什么程序显示我"was not declared in this scope"?
- 为什么我会收到"getuid was not declared in that scope"错误?
- 即使包含 <time.h 后仍"‘CLOCK_PER_SEC’ was not declared in this scope"错误>
- 我正在接受"Error: string was not declared in this scope"
- C++ 我一直在"was not declared in this scope error"
- 明确声明时显示"DialogProc not declared"错误
- 将 .ui 文件导入 Qt5 C++时出错"was not declared in this scope"
- 编译 CPP 应用程序时出错。 "error: 'posix_memalign' was not declared in this scope"
- main.cpp中的错误:函数库中的函数"not declared in this scope",但实际上是
- "Error: 'dungeon_t' was not declared in this scope"但包含在标题中
- C++ 中的" Variable ' i ' was not declared in scope "是什么?
- "pointer was not declared in this scope"是什么意思
- 学习如何在遇到错误'variable not declared in scope'的 c++ 中使用指针
- "error: not declared in this scope?"是什么意思
- 宣布时的另一个'not declared in this scope'问题
- " 'X' not declared in this scope "错误
- 子类模板错误 (C++): "error: 'root' was not declared in this scope"