模板类,并将数组初始化为零
Template classes and initializing an array to zero
我今天早些时候发布了关于模板类的文章,但离我之前的问题还有很长的路要走,并从这里得到了解决方案。当然,当这个问题得到解决时,总有一个新的问题我似乎想不出来。
给定以下构造函数:
template <typename Type, int inSize>
sortedVector<Type, inSize>::sortedVector():
size(inSize), vector(new Type[inSize]), amountElements(0)
{}
我想制作一个动态数组,然后可以通过add方法将任何类型的元素插入其中。来自main的呼叫如下所示:
sortedVector<Polygon, 10> polygons;
sortedVector<int, 6> ints;
构造数组时,如何将其初始化为零?我不能将对象设置为零;)
我觉得我很聪明,试着重载Polygon的=运算符,如果给它一个int,它什么都不会做。事实证明我做不到):
有什么好的建议吗?
此外,这里还有模板类sortedVector:
template <typename Type, int inSize>
class sortedVector
{
public:
sortedVector();
int getSize();
int getAmountElements()
bool add(const Type &element);
private:
Type *vector;
int size;
int amountElements;
};
还有Polygon:
class Polygon
{
public:
Polygon();
Polygon(Vertex inVertArr[], int inAmountVertices);
~Polygon();
void add(Vertex newVer);
double area();
int minx();
int maxx();
int miny();
int maxy();
int getAmountVertices() const;
friend bool operator > (const Polygon &operand1, const Polygon &operand2);
friend bool operator < (const Polygon &operand1, const Polygon &operand2);
private:
Vertex *Poly;
int amountVertices;
};
将数组元素初始化为Type()
。这就是标准库容器的作用。对于内置的数字类型,Type()
相当于0。对于类/结构类型,Type()
构造一个临时默认构造的对象。
您只需使用Type()
即可获得默认构造的对象。一种更好的方法是直接使用std::vector<T>
,或者通过添加所需的任何功能或约束的瘦包装器来使用。尽管没有std::vector<T>
是可行的,但任何真正正确管理资源和对象的解决方案最终都会重新实现std::vector<T>
的至少一部分。
只需将"vector"(顺便说一句,鉴于std::vector<>
的突出性,名称令人困惑)的每个元素指定为默认值。默认值仅为Type()
,因此您可以在构造函数主体中执行以下操作:
std::fill(vector, vector + size, Type());
构造数组时,如何将其初始化为零?我可以未将对象设置为零;)
您可以使用所谓的默认构造值。换句话说,您需要定义(若并没有定义的话)特殊的值,它将为您的对象扮演零的角色。
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理