C++类中如何合并同逻辑运算符重载避免代码冗余
结论
C++ 原生不支持你示例中operator(+=, -=)这种批量定义多个运算符重载的语法,C++标准从未提供过一次声明多个运算符重载的语法规则,你写的这种写法无法通过编译。
重复逻辑消除方案
你不需要为每个逻辑相近的运算符重复写遍历逻辑,常规做法是把公共的遍历、合法性校验逻辑抽成类内私有辅助模板函数,将具体运算操作作为模板参数传入,不同运算符重载仅需一行调用即可,没有额外性能损耗。
修正你原有代码的笔误(原代码存在类名写错、循环变量缺失、成员名不匹配问题)后,实现示例如下:
#include <vector> #include <functional> class Matrix { public: Matrix& operator+=(const Matrix& rhs) { apply_elementwise_op(rhs, std::plus<double>{}); return *this; } Matrix& operator-=(const Matrix& rhs) { apply_elementwise_op(rhs, std::minus<double>{}); return *this; } private: int rows_ {}; int columns_ {}; std::vector<std::vector<double>> matrix_; template<typename BinaryOp> void apply_elementwise_op(const Matrix& rhs, BinaryOp op) { // 此处可补充矩阵维度相等的校验逻辑 for (int i = 0; i < rows_; ++i) { for (int j = 0; j < columns_; ++j) { matrix_[i][j] = op(matrix_[i][j], rhs.matrix_[i][j]); } } } };
实现说明
- 模板实例化时运算逻辑会被直接内联,运行时性能和你手写重复循环完全一致,没有额外开销
- 后续如果需要扩展
*=、/=等其他元素级运算符重载,只需要新增几行调用辅助函数的代码即可,不需要重复编写双层循环 - 如果使用C++20及以上标准,也可以直接在运算符重载内传入lambda作为运算逻辑,代码会更灵活
内容的提问来源于stack exchange,提问作者notamaster
相关产品推荐
相关产品推荐

