1
我想我的數組類轉換爲模板,和我不斷收到錯誤「錯誤C2955:‘數組’:使用類模板需要模板」轉換的Array類模板
這是我的類嘗試轉換後。
// Fig. 10.10: Array.h
// Array class definition with overloaded operators.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <stdexcept>
#ifndef ARRAY_H
#define ARRAY_H
using namespace std;
template<typename T>
class Array
{
friend ostream &operator<<(ostream &, const Array &);
friend istream &operator>>(istream &, Array &);
public:
explicit Array(int arraySize = 3)// default constructor
: size(arraySize > 0 ? arraySize :
throw invalid_argument("Array size must be greater than 0")),
ptr(new T[ size ])
{
for (size_t i = 0; i < size; ++i)
ptr[ i ] = 0; // set pointer-based array element
}
~Array()// destructor
{
delete [] ptr; // release pointer-based array space
}
size_t getSize() const
{
return size; // number of elements in Array
} // end function getSize
const 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 T[ 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=
bool 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; // Arrays are equal
} // end function operator==
// subscript operator for const objects returns rvalue
T operator[](int subscript) const
{
// check for subscript out-of-range error
if (subscript < 0 || subscript >= size)
throw out_of_range("Subscript out of range");
return ptr[ subscript ]; // returns copy of this element
} // end function operator[]
private:
size_t size; // pointer-based array size
T *ptr; // pointer to first element of pointer-based array
}; // end class Array
template <typename T>
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;
} // end function
template <typename T>
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;
} // end for
if (a.size % 4 != 0) // end last line of output
output << endl;
return output; // enables cout << x << y;
} // end function operator<<
#endif
錯誤來自isteam和ostream函數。 類模板錯誤的使用似乎是我得到的唯一問題。 感謝您的幫助。
您的操作員接收並返回'Array'。唯一存在的是'Array'。 –
hlt
你的'Array'類缺少一個拷貝構造函數。你不能像這樣寫代碼:'{Array a(10);數組 a2 = a;}'沒有內存相關的問題(重新分配相同的內存兩次)。您在賦值運算符方面也存在問題,因爲您在發出對new []的調用之前釋放了內存。如果new []引發異常,則說明對象已損壞。 –
PaulMcKenzie