c++ - 覆盖数组索引运算符

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

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

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::属于函数名,运算符[]:

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

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

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

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

Complex temp = *this + i;
return temp;

假设适当的 operator+ 重载。尽管这里很难说您真正想要哪种语义,因为对于 Complex 无论如何都没有直观的索引访问。

关于c++ - 覆盖数组索引运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14830474/

相关文章:

C: realloc 由malloc创建的二维数组

c - 程序没有正确存储/返回数组

php - 在 Woocommerce 3 中访问 WC_Product protected 数据

javascript - JavaScript 类中的属性可以有多个值吗?

c++ - 将 float 与整数进行比较的符合标准的方法?

javascript - 使用原始索引枚举切片数组

c++ - 在数组索引上使用迭代器

Python __getattribute__ (或 __getattr__) 模拟 php __call

c++ tron Player lightcycle 朝一个方向移动

c++ - CString a = "Hello "+ "World!";是否可以?