c++ - 具有嵌套类的模板类

标签 c++ templates nested-class

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/

相关文章:

c++ - 如何编写代码来自动更改注册表值?

c++ - 我可以依靠 std::map::operator[] 来触摸吗?

c++ - 使用继承的类模板避免公共(public)成员不可见和源代码膨胀/重复的更好方法?

c++ - 回归虚无?

c++ - 基于模板参数的可选范围检查

c++ - 嵌套类和继承 C++

c++ - 声明后初始化对象时“不匹配调用”

c++ - 用于获取/释放资源的 JNI C++ 模板

c++ - 我想在 C++ 中为 map<> 的给定 KEY 返回一个 VALUE。如果 KEY 不在 map<> 中,返回什么?

java - 在 Java 中返回嵌套类类型