我知道在 C++ 中函数可以通过它们的 const 属性重载,但是当我运行这段代码时出现错误:
#include <iostream>
#include <conio.h>
using namespace std;
template<class T> class Array
{
public:
Array() : data(0), sz(0){}
Array(unsigned size) : sz(size), data(new T[size]){}
~Array()
{
delete[] data;
}
const T& operator[](unsigned n) const
{
if(n >= sz || data == 0)
{
throw "Array subscript out of range";
}
return data[n];
}
T& operator[](unsigned n)
{
if(n >= sz || data == 0)
{
throw "Array subscript out of range";
}
return data[n];
}
operator const T*() const
{
return data;
}
operator T*()
{
return data;
}
private:
T* data;
unsigned sz;
Array(const Array& a);
Array& operator=(const Array&);
};
int main()
{
Array<int> IntArray(20);
for(int i = 0; i != 20; ++i)
{
IntArray[i] = i;
}
return 0;
}
错误来自 IntArray[i] = i;
编译器说它找不到合适的重载函数。
它不应该调用 T& operator[](unsigned n)
吗??
我使用 vs2010 作为我的编译器
感谢您的帮助。
最佳答案
调用不明确,因为代码需要转换(索引为 int
并且您的 operator[]
需要类型为 unsigned
的值) 并且正如错误消息所说,有多种可能的转换。 (如果您没有提供 operator T*
转换运算符,就不会出现这种情况。)
error C2666: 'Array::operator []' : 4 overloads have similar conversions could be
- 'int &Array::operator [](unsigned int)'
- 'const int &Array::operator [](unsigned int) const'
- 'built-in C++ operator[(const int *, int)'
- 'built-in C++ operator[(int *, int)'
while trying to match the argument list '(Array, int)' with [T=int]
只需将您的 for 循环更改为使用 unsigned
类型的索引,以便它可以选择适当的重载。
for(unsigned i = 0; i != 20; ++i)
{
IntArray[i] = i;
}
顺便说一句,提供到指针类型的直接转换通常被认为是一个坏主意 (TM),因为它支持这种语法:
Array<int> array(20);
delete array;
关于C++函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254933/