代码之家  ›  专栏  ›  技术社区  ›  Ilya

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

  •  2
  • Ilya  · 技术社区  · 9 年前

    我用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>
    

    原因是什么?我该怎么解决?

    1 回复  |  直到 9 年前
        1
  •  2
  •   Petr    9 年前

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

    更明确地说,发生了什么

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

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

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

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