类的重载=运算符应该像矩阵一样运行

时间:2013-04-01 23:46:56

标签: c++ operator-overloading overloading

我有一个类似于矩阵的类模板。 因此,用例类似于:

Matrix matrix(10,10);
matrix[0][0]=4;
//set the values for the rest of the matrix
cout<<matrix[1][2]<<endl;

当我在构造函数中直接设置值时,它运行良好,但是当我想使用matrix[x][y]=z;时,我得到error: lvalue required as left operand of assignment。我假设,我必须重载=运算符。不过我整个晚上都试过,但我没有发现,如何实现它。请问有什么人如此友好并告诉我如何为我的代码重载=运算符,以便为该矩阵赋值?

代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sstream>

using namespace std;

class Matrix {
public:

    Matrix(int x,int y) {
        _arrayofarrays = new int*[x];
        for (int i = 0; i < x; ++i)
            _arrayofarrays[i] = new int[y];

        // works here
        _arrayofarrays[3][4] = 5;
    }

    class Proxy {
    public:

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

        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

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

private:
    int** _arrayofarrays;
};

int main() {
    Matrix matrix(5,5);

    // doesn't work :-S
    // matrix[2][1]=0;

    cout << matrix[3][4] << endl;
}

2 个答案:

答案 0 :(得分:4)

如果您打算修改代理引用的矩阵元素,那么operator[]类中Proxy的重载必须返回引用:

int& operator[](int index)

目前,您返回int,它会复制元素的值 - 而不是您想要的。还应该有const重载,以便operator[]适用于const矩阵。这个可以按价值返回:

int operator[](int index) const

实际上,size_tint更适合索引,因为它是无符号类型。你没有给负指数赋予任何特定的含义,所以禁止它们是有意义的。

除非您想一次分配整行,否则不需要重载operator=的{​​{1}}。实际上,您根本不需要Proxy类,因为您可以直接返回指向行数组的指针。但是,如果您想更改您的设计 - 例如,使用稀疏或压缩表示 - 那么Proxy将允许您保留Proxy界面。

答案 1 :(得分:3)

问题是你在proxy :: operator []中返回一个int值。你的第一个[]运算符返回代理对象,第二个返回一个int。如果你的proxy []操作符要返回一个int引用,那么你就可以分配给它:

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