1 #include <iostream>
2 using namespace std;
3 template<typename T>
4 class Top {
5 public:
6 class Sub {
7 protected:
8 T age;
9 };
10 class Derived : public Sub {
11 public:
12 void printAge() {
13 cout << age << endl;
14 }
15 };
16 };
17 int main()
18 {
19 return 0;
20 }
当我编译代码时,出现以下错误:
test.cpp: In member function ‘void Top<T>::Derived::printAge()’:
test.cpp:13:25: error: ‘age’ was not declared in this scope
cout << age << endl;
但如果不是模板,就可以了。 很高兴收到您的答复。
最佳答案
Derived 中的
age 是模板中的名称。标准定义了两种名称:
- Dependent :名称依赖于模板参数但不是 在模板中声明。
- 非依赖:不依赖于模板参数的名称,加上模板本身的名称和在其中声明的名称。
在 cout << age << endl
行, age 是一个 Non dependent 名称,应在模板定义点解析。那时,编译器仍然不知道 age 是什么,因为 Top::sub 可以/可以稍后专门化。所以它不会在基类中查找名称,而只会在封闭范围中查找。由于封闭范围内没有年龄,编译器会报错。
在 age 上添加 this-> 或 Top::使其依赖,因此查找规则发生变化。现在 age 在模板实例化时解析,编译器充分理解基类并可以正确解析名称。
关于c++ - 具有嵌套类的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19705786/