C++函数重载

标签 c++ templates operator-overloading overloading

我知道在 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/

相关文章:

templates - 如何从虚函数返回 boost::asio::deferred

c++ - 学术问题: typename

c++ - 迭代器运算符++重载C++

c++ - 重载运算符时 C++ 代码出错

c++ - 如何从另一个类调用指向成员函数的指针?

c++ - &*NULL 在 C++ 中是否定义明确?

c++ - 我想知道如何实现 + 运算符重载。我已经从我之前的问题中得出了 += 运算符重载

c++ - OpenCV imshow 段错误

c++ - 成员模板出现奇怪的 PC-Lint 错误

c++ - 为什么 remove_if( ..., lambda ) 表达式需要赋值运算符?