我正处于尝试将包含运算符重载的数组类转换为模板化类的早期阶段。目前我正在尝试将模板定义添加到类和每个函数中。但是,这应该相当简单,每当我运行程序时,都会出现范围错误。
编译器说'T'没有在这个范围内声明(我会在它发生的那一行注释错误)。该错误也会在其他函数定义上再次出现。我正在使用一个涉及模板化类的程序作为指南,它以我尝试的确切方式实现功能(这就是我感到困惑的原因)。我需要做什么来解决这个问题?
谢谢你。
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <stdexcept>
using namespace std;
#ifndef ARRAY_H
#define ARRAY_H
template <typename T>
class Array
{
public:
Array(int = 10);
Array(const Array&);
~Array();
int getSize() const;
const Array &operator=(const Array &);
bool operator==(const Array&) const;
bool operator!=(const Array &right) const
{
return ! (*this == right);
}
int &operator[](int);
int operator[](int) const;
private:
int size;
int *ptr;
};
#endif
template<typename t>
Array<T>::Array(int arraySize) //ERROR: T was not declared in this scope***********
{
if(arraySize > 0)
size = arraySize;
else
throw invalid_argument("Array size myst be greater than 0");
ptr = new int[size];
for(int i = 0; i < size; i++)
ptr[i] = 0;
}
template<typename t>
Array<T>::Array(const Array &arrayToCopy): size(arrayToCopy.size)
{
ptr = new int[size];
for(int i = 0; i < size; i++)
ptr[i] = arrayToCopy.ptr[i];
}
template<typename t>
Array<T>::~Array()
{
delete [] ptr;
}
template<typename t>
int Array<T>::getSize() const
{
return size;
}
template<typename t>
const Array<T> &Array::operator=(const Array &right)
{
if (&right != this)
{
if(size != right.size)
{
delete [] ptr;
size = right.size;
ptr = new int[size];
}
for(int i = 0; i < size; i++)
ptr[i] = right.ptr[i];
}
return *this;
}
template<typename t>
bool Array<T>::operator==(const Array &right) const
{
if(size != right.size)
return false;
for(int i = 0; i < size; i++)
if(ptr[i] != right.ptr[i])
return false;
return true;
}
template<typename t>
int &Array<T>::operator[](int subscript)
{
if(subscript < 0 || subscript >= size)
throw out_of_range("Subscript out of range");
return ptr[subscript];
}
template<typename t>
int Array<T>::operator[](int subscript) const
{
if(subscript < 0 || subscript >= size)
throw out_of_range("Subscript out of range");
return ptr[subscript];
}
int main()
{
//main is empty at the moment because I want to make sure that the class is functional
//before implementing the driver function.
system("pause");
}