使用我的数组时出现奇怪的警告 class

Strange warnings when using my array class

我用 C++ 编写了一个非常简单的数组 class 并在我的应用程序中使用它:

/* 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>

这是什么原因?我该如何解决?

原因很简单:对于你的filename[0],编译器可以使用你的operator[],或者它可以使用你的类型转换运算符将filename转换为char*,然后将 operator[] 应用于 char 指针。

更明确地说,发生的事情是

filename.Array<char>::operator[](0)

filename.Array<char>::operator char*().operator[](0)

(不知道后者是否是正确的 c++,但它给出了发生了什么的想法)

P.S。几乎可以肯定这应该是以前问过的,但找不到重复项。