Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 没有默认构造函数的模板的模板_C++_Templates - Fatal编程技术网

C++ 没有默认构造函数的模板的模板

C++ 没有默认构造函数的模板的模板,c++,templates,C++,Templates,我正在尝试编写一个没有默认构造函数的模板类。 对于A工作正常,但是对于A我不知道如何让它工作 1 #include <iostream> 2 using namespace std; 3 4 template <typename T> 5 class A { 6 T x; 7 8 public: 9 A(T y) { x = y; } 10 }; 11 12 int main()

我正在尝试编写一个没有默认构造函数的模板类。
对于
A
工作正常,但是对于
A
我不知道如何让它工作

  1   #include <iostream>
  2   using namespace std;
  3 
  4   template <typename T>
  5   class A {
  6     T x;
  7 
  8    public:
  9     A(T y) { x = y; }
 10   };
 11 
 12   int main() {
 13     A<int> a(0);
 14     A<A<int> > b(A<int>(0));
 15 
 16     return 0;
 17   }
1#包括
2使用名称空间标准;
3.
4模板
5甲级{
6tx;
7.
8公众:
9a(ty){x=y;}
10   };
11
12 int main(){
13a(0);
14ab(A(0));
15
16返回0;
17   }
来自clang的错误列表

    test.cpp:9:5: error: constructor for 'A<A<int> >' must explicitly initialize the member 'x' which does not have a default constructor
        A(T y) { x = y; }
        ^
    test.cpp:14:16: note: in instantiation of member function 'A<A<int> >::A' requested here
        A<A<int> > b(A<int>(0));
                   ^
    test.cpp:6:7: note: member is declared here
        T x;
          ^
    test.cpp:5:9: note: 'A<int>' declared here
      class A {
            ^
test.cpp:9:5:错误:“A”的构造函数必须显式初始化没有默认构造函数的成员“x”
A(ty){x=y;}
^
test.cpp:14:16:注意:在这里请求的成员函数'A::A'的实例化中
ab(A(0));
^
测试。cpp:6:7:注:此处声明成员
tx;
^
test.cpp:5:9:注:此处声明为“A”
甲级{
^

您没有在构造函数的初始值设定项列表中正确构造
x
,因此
A(ty)
必须在调用
操作符=
y
复制分配给它之前默认构造
x

int
提供了一个默认构造函数,它只允许值未初始化,但
a
不允许

您的构造函数应该是

A(T y) : x(y) { }

您没有在构造函数的初始值设定项列表中正确构造
x
,因此
A(ty)
必须在调用
operator=
y
复制分配给它之前默认构造
x

int
提供了一个默认构造函数,它只允许值未初始化,但
a
不允许

您的构造函数应该是

A(T y) : x(y) { }