【发布时间】:2013-03-26 18:12:29
【问题描述】:
我正处于尝试将包含运算符重载的数组类转换为模板化类的早期阶段。目前我正在尝试将模板定义添加到类和每个函数中。这应该相当简单,但是,每当我运行程序时,都会出现范围错误。
编译器说 `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");
}
【问题讨论】:
-
永远不要在标题中使用“使用命名空间...”。这被认为是非常糟糕的形式。
-
这不是真正的标题。我目前只使用一个 .cpp 文件,直到我将其分开。
标签: c++ arrays templates scope