首页 > 解决方案 > 在模板类中构造一个类

问题描述

我正在研究模板和 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.

但我想知道为什么会出现错误,我该如何解决上面代码中的错误请帮助我?

感谢您的帮助。

标签: c++

解决方案


如果要在类的定义中初始化变量,则必须使用赋值语法或花括号。不允许使用简单的括号。

typename type::in ob=typename type::in(3);
type ob1=type(4,4);

typename type::in ob{3};
type ob1{4,4};

这与模板无关,对所有类都一样。原因之一是使编译器的解析更容易。正如评论中提到的那样,最令人头疼的解析是一个示例,当可以通过使用{}而不是来完成初始化和函数声明之间的歧义时()


推荐阅读