我用C ++编写了一个非常简单的数组类,并在我的应用程序中使用它:
/* A simple array class template that performs dynamic */
/* memory management and casting to (T*), which allows */
/* to use it as a usual array. */
template <typename T>
class Array
{
public:
//Constructor
Array(unsigned long size)
{
try
{
data = new T[size];
m_size = size;
}
catch(...)
{
cout << "Could not allocate " << size << " bytes." << endl;
data = NULL; m_size = 0;
}
}
//Typecast operator
operator T*() { assert(data!=NULL); return data; }
//Subscript operator
T& operator[] (unsigned long Index);
//Destructor
~Array() { if(data!=NULL) delete[] data; }
private:
T * data;
unsigned long m_size;
};
template<typename T>
T& Array<T>::operator[] (unsigned long Index)
{
assert(Index<m_size);
assert(data!=NULL);
return data[Index];
}
然而,当我像这样使用它时:
Array<char> filename(5);
filename[0] = SomeVar;
GCC输出以下警告:
warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
note: candidate 1: T& Array<T>::operator[](long unsigned int) [with T = char]
note: candidate 2: operator[](char*, int) <built-in>
是什么原因?我该如何解决?
答案 0 :(得分:2)
原因很简单:对于您的filename[0]
,编译器可以使用您的operator[]
,也可以使用您的类型转换运算符将filename
转换为char*
,然后将operator[]
应用于char
指针。
更明确地说,发生了什么
filename.Array<char>::operator[](0)
VS
filename.Array<char>::operator char*().operator[](0)
(不知道后者是否是正确的c ++,但它可以了解发生了什么)
P.S。几乎可以肯定这应该在之前被问到,但是找不到重复。