c++ - 如何识别赋值运算符?

标签 c++ operator-overloading

我有重载 [] 的类,当我尝试将值设置为数组时,我需要让它能够识别。我假设,我将不得不重载运算符 =,但我不知道,整个东西会是什么样子。我的部分代码:

class Matrix {
public:

Matrix(int x, int y);
~Matrix(void);
Matrix& operator =(const Matrix &matrix); //ok...this is probably wrong...

class Proxy {
public:

    Proxy(double* _array) : _array(_array) {
    }

    double &operator[](int index) const {
        return _array[index];
    }

private:
    double* _array;
};

Proxy operator[](int index) const {
    return Proxy(_arrayofarrays[index]);
}

Proxy operator[](int index) {
    return Proxy(_arrayofarrays[index]);
}

int x, y;
double** _arrayofarrays;
};

所以当我尝试设置 Matrix matrix(3,3); 时,我只需要能够识别;矩阵[0][0]=1; 其他一切正常,所以我认为不需要粘贴整个代码

最佳答案

看起来你想要一些不可能直接实现的东西:operator[][].

您可以使用中间类来模拟此行为:
由于 Matrix 类通常索引为 [行][列],您可以
让第一个运算符方法返回相应的 Row 对象。
行类可以重载 operator[] 并返回相应的
元素。

Row& Matrix::operator[](int r);  
double& Row::operator[](int c);

现在当您创建矩阵对象时,您可以按预期对其进行索引:

Matrix matrix(3,3);  
matrix[0][0] = 1;

最后一行等同于调用:

matrix.operator[](0).operator[](0) = 1;

要检查越界索引,请存储矩阵大小:

Proxy operator[](int index) {
    assert(index < num_rows);
    return Proxy(_arrayofarrays[index]);
}

double &operator[](int index) const {
    assert(index < num_cols);
    return _array[index];
}

正如 Aldo 所建议的,Proxy 可以在其构造函数中传递数组长度值:

 Proxy(double* _array, int _length) : _array(_array), num_cols(_length){
 }

根据一般经验,如果您将原始数组传递给函数,您几乎总是希望同时传递该数组的长度。

关于c++ - 如何识别赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771912/

相关文章:

c++ - 复制构造函数 Big 3 C++ 问题

c++ - 如何找到包含所有给定框的框?

c++ - 如何使用 libav* 将 KLV 数据包编码为 H.264 视频

c++ - 数组溢出 C++(在 arr[0])?

c++ - #在c++中定义一个特殊的运算符

c++ - 如何为随机访问迭代器实现 "less than operator"?

c++ - 从友元函数返回局部变量的引用

c# - 泛型和 "One of the parameters of a binary operator must be the containing type"错误

c++ - 我有一个具有不同前缀的相关函数的 C 库。派生的 C++ 类如何在不重复代码的情况下调用它们?

c++ - C 或 C++ 中的 Csing for