数组模板类对象
C++ - Array og template class objects
我的任务是:
实现模板类cuboid,其中尺寸(宽度,长度和高度)可以是任何数据类型。cuboid数组也可能是模板函数的实参,因此有必要重载所需的操作符。编写主程序,其中长方体数组将被声明并初始化为数据类型为float的维数。
下面是我的代码:#include <iostream>
using namespace std;
template <class T>
class cuboid{
private:
T length, width, height;
cuboid *arr;
int length_of_array;
public:
cuboid();
cuboid(cuboid*, int);
cuboid(T, T, T);
~cuboid();
T volume(cuboid);
cuboid& operator = (const cuboid&);
};
template <class T>
cuboid<T>::cuboid(){
}
template <class T>
cuboid<T>::cuboid(cuboid *n, int len){
length_of_array = len;
arr = new cuboid <T> [length_of_array];
for(int i = 0; i < length_of_array; i++){
arr[i] = n[i];
}
}
template <class T>
cuboid<T>::cuboid(T o, T s, T v){
length = o;
width = s;
height = v;
}
template <class T>
cuboid<T>::~cuboid(){
delete [] arr;
arr = 0;
}
template <class T>
T cuboid<T>::volume(cuboid b){
if(length * width * height > b.length * b.width * b.height){
return length * width * height;
}
else{
return b.length * b.width * b.height;
}
}
template <class T>
cuboid<T> & cuboid<T>::operator=(const cuboid& source){
length = source.length;
width = source.width;
height = source.height;
return *this;
}
int main(){
int length;
float a, b, c;
cout << "How many cuboids array has? " << endl;
cin >> length;
cuboid<float> *arr;
arr = new cuboid <float> [length];
for(int i = 0;i < length; i++){
cin >> a >> b >> c;
arr[i] = cuboid <float> (a,b,c);
}
cuboid <float> n(arr, length);
}
我成功地编译了它,但是当我开始输入数组对象的尺寸时,程序崩溃了。任何想法?
提前感谢。
编辑:我修改了原代码(和问题的表述),将矩形改为长方体
问题在于这一行代码(连同析构函数):
arr[i] = rectangle <float> (a,b,c);
它使用不分配 紧接着调用析构函数: 尝试 一个解决方案是修改析构函数,使其考虑到这种情况。arr
数组(根据您的实现存储在堆上)的构造函数在堆栈上分配新的矩形对象。template <class T>
rectangle<T>::~rectangle() {
std::cout << "D1" << std::endl;
delete[] arr;
arr = 0;
}
delete[]
和arr
,尽管在这种情况下它还没有被分配。
相关文章:
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组