0

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

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 <<
4

2 回答 2

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无论如何都没有直观的索引访问。

于 2013-02-12T10:38:16.763 回答
2

代替

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

它应该是

const Complex& Complex::operator[](unsigned int i) const
于 2013-02-12T10:41:10.490 回答