在模板类中构造类
Constructing a class in a template class
我正在研究模板和 typename 关键字,我在以下代码中出现错误:
/*1)*/ #include<iostream>
/*2)*/ #include<cstdio>
/*3)*/ #include<stdlib.h>
/*4)*/
/*5)*/ using namespace std;
/*6)*/
/*7)*/ class out
/*8)*/ {
/*9)*/ public:
/*10)*/ int i;
/*11)*/ out(int i,int j):i{i},ob{j}{}
/*12)*/ class in
/*13)*/ {
/*14)*/ public:
/*15)*/ int j;
/*16)*/ in(int j):j{j}{}
/*17)*/ }ob;
/*18)*/ };
/*19)*/
/*20)*/ template<typename type>
/*21)*/ class temp
/*22)*/ {
/*23)*/ public:
/*24)*/ typename type::in ob(3);
/*25)*/ type ob1(4,4);
/*26)*/ };
/*27)*/
/*28)*/ int main()
/*29)*/ {
/*30)*/ out ob(1,1);
/*31)*/ out::in ob1(2);
/*32)*/ temp<out> t;
/*33)*/ cout<<ob.i<<" "<<ob.ob.j<<endl;
/*34)*/ cout<<ob1.j<<endl;
/*35)*/ cout<<t.ob.j<<endl;
/*36)*/ cout<<t.ob1.i<<" "<<t.ob1.ob.j;
/*37)*/ }
代码显示以下错误
Line Error
|24| error: expected identifier before numeric constant
|24| error: expected ',' or '...' before numeric constant
|25| error: expected identifier before numeric constant
|25| error: expected ',' or '...' before numeric constant
In function 'int main()':
|35| error: 't.temp<type>::ob<out>' does not have class type
|36| error: 't.temp<type>::ob1<out>' does not have class type
|36| error: 't.temp<type>::ob1<out>' does not have class type
=== Build failed: 7 error(s), 0 warning(s) (0 minute(s), 4 second(s)) ===
如果我改变两行
类型名称类型::在 ob(3(;
类型 ob1(4,4(;
自
类型名称类型::IN ob=类型名称类型::in(3(;
OB1 型 = 型(4,4(;
它将正常工作并产生以下输出:
1 1
2
3
4 4
Process returned 0 (0x0) execution time : 0.847 s
Press any key to continue.
但是我想知道为什么会出现错误,如何解决上述代码中的错误请帮助我?
感谢您的帮助。
如果要初始化类定义中的变量,则必须使用赋值语法或大括号。不允许出现普通偏执。
typename type::in ob=typename type::in(3);
type ob1=type(4,4);
typename type::in ob{3};
type ob1{4,4};
这与模板无关,并且对所有类的工作方式相同。原因之一是使编译器更容易解析。如注释中所述,最令人烦恼的解析是一个例子,当可以使用{}
而不是()
来消除初始化和函数声明之间的歧义时。
相关文章:
- 没有找到相关文章