C++ 模板化对象数组
我的任务是: 实现表示长方体的模板类,其中长度、宽度和高度可以是任何数据类型。 长方体数组也可以作为模板函数的参数,所以重载所有需要的运算符。 当比较长方体时,体积越大,体积越大 以下是我所做的:C++ 模板化对象数组,c++,arrays,templates,C++,Arrays,Templates,我的任务是: 实现表示长方体的模板类,其中长度、宽度和高度可以是任何数据类型。 长方体数组也可以作为模板函数的参数,所以重载所有需要的运算符。 当比较长方体时,体积越大,体积越大 以下是我所做的: #include <iostream> using namespace std; template <class T> class cuboid{ private: int length_of_array; T length, width, height;
#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);
}
我无法编译它,因为主程序中的最后一行。有什么想法吗?对于长方体,您有一个接受int*、int参数的构造函数,而不是长方体*、int。您应该编写一个副本构造函数:
cuboid(const cuboid<T>&);
或者不鼓励提供getter来访问内部阵列:
const T* get_arr() const;
如果查看编译错误,请将cuboid::cuboidT*,int构造函数更改为const T*:
main.cpp:70:31: error: no matching function for call to 'cuboid<int>::cuboid(cuboid<int>*&, int&)'
cuboid <int> arr(n, length);
^
编写一个既为长方体又为长方体集合的类,即使编写正确,也显然违反了的规定。您应该显示准确的错误消息以及代码。最后一行需要一个采用长方体*和int的构造函数。您没有这样的构造函数。嗯,我认为他需要一个来自cuboid*的构造函数,在这种情况下,不是复制构造函数。@BlackCat复制构造函数在这种情况下最为惯用,在取消引用后仍然可以使用指针。然而,我在回答中提到的第二个选择是,你所说的期望值是常量。
main.cpp:70:31: error: no matching function for call to 'cuboid<int>::cuboid(cuboid<int>*&, int&)'
cuboid <int> arr(n, length);
^
template <class T>
class cuboid {
private:
T length, width, height;
};
std::vector<cuboid<int>> cuboids;
for (int i = 0; i < length; ++i) {
cin >> a >> b >> c;
cuboids.push_back(cuboid(a, b, c));
}