我正在尝试编写一个没有默认构造函数的模板类。
对于 A<int>
工作正常,但对于 A<A<int>>
我不知道如何让它工作。
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 }
来自 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 {
^
最佳答案
您没有正确构建 x
在构造函数的初始化列表中,因此 A(T y)
必须默认构造 x
在调用之前 operator=
复制分配 y
int
提供了一个默认构造函数,它只是让值未初始化,但是A<int>
没有。
你的构造函数应该是
A(T y) : x(y) { }
关于c++ - 没有默认构造函数的模板的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261448/