模板化对象的数组

时间:2015-08-31 15:01:44

标签: c++ arrays templates

这是我的任务:

实现将代表长方体的模板类,其中长度,宽度和高度可以是任何数据类型。 长方体数组也可以是模板函数的参数,因此需要重载所有需要的运算符。 (当比较长方体时,较大的是具有较大体积的长方体)

这是我做的:

#include <iostream>

using namespace std;

template <class T>
class cuboid{
private:
    int length_of_array;
    T length, width, height;
    T * arr;
public:
    cuboid();
    cuboid(T *, int);
    cuboid(T, T, T);
    ~cuboid();
    cuboid(const cuboid &);
    T volume();
};

template <class T>
cuboid<T>::cuboid(){
}

template <class T>
cuboid<T>::cuboid (T *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(){
    return length * width * height;
}

template <class T>
cuboid<T>::cuboid(const cuboid & source){
    length_of_array = source.length_of_array;
    arr = new cuboid <T> [length_of_array];
    for(int i = 0; i < length_of_array; i++){
    arr[i] = source.arr[i];
    }
}

int main(){
    int a, b, c, length;
    cuboid <int> *n;
    cout << "How many cuboids array contains? " << endl;
    cin >> length;
    n = new cuboid <int> [length];
    for(int i = 0; i < length; i++){
    cin >> a >> b >> c;
    n[i] = cuboid <int> (a,b,c);
    }
    cuboid <int> arr(n, length);
}

我无法编译它(因为主程序中的最后一行)。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果你看一下你的编译错误:

main.cpp:70:31: error: no matching function for call to 'cuboid<int>::cuboid(cuboid<int>*&, int&)'
     cuboid <int> arr(n, length);
                               ^

它告诉您,您没有合适的构造函数。您正试图致电cuboid<int>(cuboid<int>*, int),但您所拥有的只是cuboid<int>(int*, int)。现在,我可以告诉你如何解决这个问题,但我会修复你的另一个问题:你的设计。

你的问题是:

  

实现将代表长方体的模板类,其中长度,宽度和高度可以是任何数据类型。

你的部分解决方案非常有意义:

template <class T>
class cuboid {
private:
    T length, width, height;
};

但为什么T*和长度?阵列是什么?为什么要将该数组分配给构造函数中的cuboid*?该代码仅编译,因为您从未实例化该构造函数。如果你想要一个cuboid的集合,正确的方法是使用容器类。类似的东西:

std::vector<cuboid<int>> cuboids;
for (int i = 0; i < length; ++i) {
    cin >> a >> b >> c;
    cuboids.push_back(cuboid(a, b, c));
}

写一个两个一个cuboid 的集合,即使你写得正确,也很明显违反{ {3}}

答案 1 :(得分:0)

对于cuboid<int>,您有一个接受int*, int参数的构造函数,而不是cuboid<int>*, int。你应该写一个拷贝构造函数:

cuboid(const cuboid<T>&);

或(在这种情况下更直接)来自另一个cuboid指针的构造函数:

cuboid(const cuboid<T>*) 

或(不鼓励)提供访问内部数组的getter:

const T* get_arr() const;

(并将cuboid<T>::cuboid(T*, int)构造函数更改为const T*)。