小编Sti*_*RAN的帖子

重载函数调用运算符 () 用于模板对象的索引和赋值

我正在尝试为矩阵数据结构创建模板,并且我希望以简洁直观的方式来索引和分配元素(即 'A(i,j)' 返回一个元素和 'A(i,j)=x ' 为该元素分配一个值。)

根据其他论坛主题,我看到通过引用返回数组元素,函数/运算符可以以这种方式返回和更改该元素。

template <typename T, int Rows, int Cols>
    struct Matrix {
        private:
        public:
            const int rows = Rows; //number of rows
            const int cols = Cols; //number of columns
            T data[Rows*Cols];     //contents of matrix

            //Single element indexing and assigment
            T& operator() (int i, int j) {
                return data[ (i-1)*(this->cols) + j ];
            }
    };

int main(){
    const int m = 3;
    const int n = 4;
    Matrix<float, m, n> A;

    for (int i = …
Run Code Online (Sandbox Code Playgroud)

c++ templates operator-overloading

0
推荐指数
1
解决办法
44
查看次数

标签 统计

c++ ×1

operator-overloading ×1

templates ×1