c – 具有嵌套类的模板类
发布时间:2020-12-16 07:06:17 所属栏目:百科 来源:网络整理
导读:1 #include iostream2 using namespace std;3 templatetypename T4 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
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<<年龄<< endl,age是一个非依赖名称,应在模板定义的点处解析.此时,编译器仍然不知道年龄是多少,因为Top :: sub可以/稍后可以专用.因此它不会在基类中查找名称,而只是在封闭范围内.由于封闭范围内没有年龄,编译器会抱怨. 添加此 – >或者Top :: on age使其依赖,因此查找规则会发生变化.现在,在模板实例化时解决了年龄问题,编译器完全理解了基类,并且可以正确地解析名称. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
