c++ - 如何为 a[x][y] 形式创建重载运算符?

标签 c++ overloading

<分区>

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

例如:

Matrix a;

a[1][2] = 5;

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

最佳答案

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

更新(2013 年 9 月 26 日):我对代码进行了很多改进。

模板中的类型T只需要满足一个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(); }
};

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

#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;
}

只为您提供一个测试此用法的示例:

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;
}

关于c++ - 如何为 a[x][y] 形式创建重载运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15598597/

相关文章:

c++ - 如何根据不同的参数定义相同的宏函数

c++ - 我可以在 C++ 中使用 “for … else” 循环吗?

c++ - 将指针地址转换为 int

php - 方法重载和类继承

c++ - 简化重载的类函数

c# - 向界面添加新功能

Java 是否有用于指定传递给方法的零值或一个值的语法?

c++ - 在短时傅里叶变换中获取特定频率的值

c++ - 如何打印混合 ascii 字符和 unicode 的字符串的每个字符?

c++ - 为什么最负的 int 值会导致关于不明确的函数重载的错误?