重载[] []运算符 [英] overloading [][] operators in c++

查看:174
本文介绍了重载[] []运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中编写一个矩阵3x3类。<​​/ p>

glm :: mat3提供通过 [] [] operator 语法。

eg myMatrix [0] [0] = 1.0f; 会将第一行第一列条目设置为 1.0f



我想提供类似的访问。我如何重载 [] []运算符 s?



错误:




运算符名称必须声明为函数




  const实数运算符[] [](int row,int col)const 
{
//应该为超出范围索引
return((row> = 0&& row< = 2)&&(col> = 0&& col< = 2) _data [row] [col]:0.0f;
}

重载此运算符的正确方法是什么?

解决方案

没有运算符 [] [] ,因此您需要重载 [] 运算符两次:一次在矩阵上,返回 / a>对象,对于返回的代理行为一次:

  // Matrix的运算符[] 
const row_proxy operator [](int row)const
{
return row_proxy(this,row);
}
//代理的运算符[]
const实数运算符[](int col)const
{
//代理存储指向矩阵的指针,到第一[]运算符
return((this-> row> = 0&& this-> row< = 2)&&(col> = 0&& col = 2))? this-> matrix-> _data [this-> row] [col]:0.0f;
}


I'm writing a matrix 3x3 class in c++.

glm::mat3 provides access to matrix data through the [][] operator syntax.
e.g. myMatrix[0][0] = 1.0f; would set the first row, first column entry to 1.0f.

I'd like to provide similar access. How can I overload the [][] operators?

I've tried the following, but I get errors:

operator name must be declared as a function

const real operator[][](int row, int col) const
{
    // should really throw an exception for out of bounds indices
    return ((row >= 0 && row <= 2) && (col >= 0 && col <= 2)) ? _data[row][col] : 0.0f;
}

What's the correct way to overload this operator?

解决方案

There is no operator [][], so you need to overload the [] operator twice: once on the matrix, returning a surrogate object for the row, and once for the returned surrogate row:

// Matrix's operator[]
const row_proxy operator[](int row) const
{
    return row_proxy(this, row);
}
// Proxy's operator[]
const real operator[](int col) const
{
    // Proxy stores a pointer to matrix and the row passed into the first [] operator
    return ((this->row >= 0 && this->row <= 2) && (col >= 0 && col <= 2)) ? this->matrix->_data[this->row][col] : 0.0f;
}

这篇关于重载[] []运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆