没有默认构造函数的模板的模板
template of template without default constructor
>我正在尝试编写一个没有默认构造函数的模板类。
对于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)
必须在调用operator=
之前默认构造x
以将赋y
复制到它。
int
提供了一个默认构造函数,它只允许值未初始化,但A<int>
没有。
您的构造函数应该是
A(T y) : x(y) { }
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 构造函数默认公共和私有变量
- 类模板构造函数默认参数
- 构造函数默认参数
- C++模板构造函数默认参数
- 在c++中设置构造函数默认值
- c++构造函数默认参数
- C++构造函数默认值头文件