gpt4 book ai didi

c++ - 在模板类中构造类

转载 作者:行者123 更新时间:2023-12-01 14:49:03 26 4
gpt4 key购买 nike

我正在研究模板和 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++ - 在模板类中构造类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com