c++ - 在模板类中构造一个类
问题描述
我正在研究模板和 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)) ===
如果我改变这两行
typename type::in ob(3);
输入 ob1(4,4);
至
typename type::in ob=typename type::in(3);
类型 ob1=type(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};
这与模板无关,对所有类都一样。原因之一是使编译器的解析更容易。正如评论中提到的那样,最令人头疼的解析是一个示例,当可以通过使用{}
而不是来完成初始化和函数声明之间的歧义时()
。
推荐阅读
- c - 结构类型数组的动态分配
- javascript - 通过 javascript 在博客文章标题中赋值
- c# - 使用会话禁用下拉列表中的项目,直到单击按钮
- web-services - Camel cxf webservice - 获取响应的问题
- javascript - slickgrid 的简单排序示例
- laravel - 使用 laravel 最佳方法排队批量翻译
- python - GPU 上的 XGBoost 正在杀死内核(在 Ubuntu 上)
- android - 如何通过捕获图像来读取或获取数据?
- javascript - Javascript注入将项目添加到购物篮
- java - 如何对对象列表进行排序?