我想覆盖类中的数组索引运算符。以下是我想做的,但没有成功。
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 <<
您的函数定义语法错误:
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
的直观索引访问。
而不是
Complex Complex::const& operator[](unsigned int i) const
应该是
const Complex& Complex::operator[](unsigned int i) const