【发布时间】:2018-05-01 19:48:10
【问题描述】:
所以,我正在尝试将一个数组类转换为一个模板类,到目前为止,我已经将头文件和主文件代码合二为一,只生成了包含所有 .cpp 代码的头文件。尽管尝试将代码编译到主文件中会导致无数错误。现在,请在这里放轻松,我仍然在这里掌握 C++,并且一些更高的功能和能力超出了我的想象,所以我提前道歉,我对所有功能都不是超级熟悉。代码如下。
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
#include <iomanip>
#include <stdexcept>
using namespace std;
template <typename GArray>
class Array
{
friend std::ostream &operator<<(std::ostream &, const Array &);
friend std::istream &operator>>(std::istream &, Array &);
public:
// default constructor for class Array (default size 3)
template <typename GArray> Array::Array(int arraySize)
: size(arraySize > 0 ? arraySize :
throw invalid_argument("Array size must be greater than 0")),
ptr(new int[size])
{
for (size_t i = 0; i < size; ++i)
ptr[i] = 0; // set pointer-based array element
} // end Array default constructor
template <typename GArray> Array::~Array()
{
delete[] ptr; // release pointer-based array space
} // destructor
size_t Array::getSize() const
{
return size; // number of elements in Array
} // end function getSize
// overloaded assignment operator;
// const return avoids: ( a1 = a2 ) = a3
template <typename GArray> const Array &Array::operator=(const Array &right)
{
if (&right != this) // avoid self-assignment
{
// for Arrays of different sizes, deallocate original
// left-side Array, then allocate new left-side Array
if (size != right.size)
{
delete[] ptr; // release space
size = right.size; // resize this object
ptr = new int[size]; // create space for Array copy
} // end inner if
for (size_t i = 0; i < size; ++i)
ptr[i] = right.ptr[i]; // copy array into object
} // end outer if
return *this; // enables x = y = z, for example
} // end function operator=
template <typename GArray> bool operator==(const Array &) const; // equality operator
// subscript operator for const objects returns rvalue
int operator[](int) const;
private:
size_t size;
int *ptr;
};
template <typename GArray> bool Array::operator==(const Array &right) const
{
if (size != right.size)
return false; // arrays of different number of elements
for (size_t i = 0; i < size; ++i)
if (ptr[i] != right.ptr[i])
return false; // Array contents are not equal
return true;
}
template <typename GArray> int Array::operator[](int subscript) const
{
if (subscript < 0 || subscript >= size)
throw out_of_range("Subscript out of range");
return ptr[subscript];
}
template <typename GArray> istream &operator>>(istream &input, Array &a)
{
for (size_t i = 0; i < a.size; ++i)
input >> a.ptr[i];
return input; // enables cin >> x >> y;
}
template <typename GArray> ostream &operator<<(ostream &output, const Array &a)
{
// output private ptr-based array
for (size_t i = 0; i < a.size; ++i)
{
output << setw(12) << a.ptr[i];
if ((i + 1) % 4 == 0) // 4 numbers per row of output
output << endl;
}
if (a.size % 4 != 0) // end last line of output
output << endl;
return output; // enables cout << x << y;
}
#endif
【问题讨论】:
-
您的模板,它们没有任何用途。你想达到什么目的?
-
拥有它以便函数可以处理所有变量类型,int、double、char 等。
-
问题是什么?要我们调试代码吗?