覆盖数组索引运算符

时间:2013-02-12 10:34:56

标签: c++ arrays class multidimensional-array operator-overloading

我想在我的类中覆盖数组索引运算符。这是我想要做的,但没有成功。

class Complex{              
    Complex const& operator[](unsigned int) const; // Read-only access
    Complex& operator[](unsigned int);             // Read/Write access:
};

const Complex& Complex::operator [](unsigned int unsignedInt) const {
    const Complex* temp = this+i;
    return *temp;
}
Complex& Complex::operator [](unsigned int unsignedInt) {
    Complex* temp = this+i;
    return *temp;
}

编辑: 我想做点什么:

Complex **c = new Complex[5];    //Create 2D array
c[2] = new Complex();            //Initialize
cout<<*c[2];                     //print by overloading <<

2 个答案:

答案 0 :(得分:3)

您的函数定义语法错误:

Complex Complex::const& operator[](unsigned int i) const{

返回类型应该由const&注释,显式名称限定Complex::属于函数名称operator[]

Complex const& Complex::operator[](unsigned int i) const {

此外,实现似乎是错误的:

const Complex* temp = this+i;
return *temp;

这没有多大意义。你可能的意思是:

Complex temp = *this + i;
return temp;

假设适当的operator+超载。虽然很难说你真正想要哪种语义,因为无论如何都没有Complex的直观索引访问。

答案 1 :(得分:2)

而不是

Complex Complex::const& operator[](unsigned int i) const

应该是

const Complex& Complex::operator[](unsigned int i) const