如何为表单a [x] [y]创建重载运算符?

Mic*_*ovi 4 c++ overloading

我有一个简单的Matrix类,我必须以格式读/写a[index1][index2].

例如:

Matrix a;

a[1][2] = 5;
Run Code Online (Sandbox Code Playgroud)

我如何在C++中实现它?谢谢.

Moh*_*oun 6

这是一个很好的基础实现,可以完全满足您的需求.

更新(2013年9月26日):我已经对代码进行了大量改进.

T模板中的类型只需满足a的要求std::vector.

#include <vector>
#include <stdexcept>

template<typename T>
class matrix {
    class row {
        std::vector<T> values;
    public:
        row(std::size_t n)
            : values(n, T()) {}

        T& operator[] (std::size_t index) {
            if (index < values.size())
                return values[index];
            else
                throw std::domain_error("Matrix column index out of bounds.");
        }
        const T& operator[] (std::size_t index) const {
            if (index < values.size())
                return values[index];
            else
                throw std::domain_error("Matrix column index out of bounds.");
        }

        std::size_t size() const { return values.size(); }
    };

    std::vector<row> rows;

public:
    matrix(std::size_t m, std::size_t n)
        : rows(m, row(n)) {}

    row& operator[](std::size_t index) {
        if (index < rows.size())
            return rows[index];
        else
            throw std::domain_error("Matrix row index out of bounds.");
    }
    const row& operator[](std::size_t index) const {
        if (index < rows.size())
            return rows[index];
        else
            throw std::domain_error("Matrix row index out of bounds.");
    }

    std::size_t row_count() const { return rows.size(); }
    std::size_t col_count() const {
        if (rows.size()) return rows[0].size();
        return 0;
    }

    std::size_t size() const { return row_count() * col_count(); }
};
Run Code Online (Sandbox Code Playgroud)

为方便起见,此助手可用于打印矩阵.

#include <ostream>

template<typename T>
std::ostream& operator <<(std::ostream& o, const matrix<T>& mat) {
    for (std::size_t i = 0u; i < mat.row_count(); ++i) {
        for (std::size_t j = 0u; j < mat.col_count(); ++j) {
            o << mat[i][j] << ' ';
        }
        o << '\n';
    }
    return o;
}
Run Code Online (Sandbox Code Playgroud)

只为你,一个用例来测试这个:

int main() {
    matrix<int> mat_0(2, 3);
    matrix<double> mat_1(1, 2);

    mat_0[0][0] = 2;
    mat_0[0][1] = 3;
    mat_0[0][2] = 4;
    mat_0[1][0] = 3;
    mat_0[1][1] = 7;
    mat_0[1][2] = 9;

    mat_1[0][0] = 0.43;
    mat_1[0][1] = 213.01;

    std::cout << mat_0;
    std::cout << '\n';
    std::cout << mat_1;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*eld 6

您需要重载,Matrix::operator[]以便它返回一个表示矩阵中列的辅助类.该辅助类也应该重载operator[]以访问该列中的元素.

但是,以这种方式实现它可能过于复杂.相反,它可能更容易实现operator(),并将两个索引作为参数:

int& Matrix::operator()(int i, int j)
{
  return internal_array[i][j];
}
Run Code Online (Sandbox Code Playgroud)