数组模板类对象

C++ - Array og template class objects

本文关键字:对象 数组      更新时间:2023-10-16

我的任务是:

实现模板类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,尽管在这种情况下它还没有被分配。

一个解决方案是修改析构函数,使其考虑到这种情况。