C++ 'this' and operator overloading

心已入冬 提交于 2019-12-11 10:55:27

问题


I was wondering how can you use operators along with 'this'. To put an example:

class grd : clm
{ 
    inline int &operator()(int x, int y) { return g[x][y]; }
    /* blah blah blah */ 
};

grd grd::crop(int cx1, int cy1, int cx2, int cy2)
{
    grd ngrd(abs(cx1-cx2), abs(cy1-cy2));
    int i, j;
    //
    for (i = cx1; i < cx2; i++)
    {
        for (j = cy1; j < cy2; j++)
        {
            if (i >= 0 && i < x && j >= 0 && j < y)
                ngrd(i-cx1,j-cy2) = ?? // this->(i,j); ****
        }
    }
    return ngrd;
}

Thanks!


回答1:


Either: this->operator()(i,j) or (*this)(i,j)




回答2:


Just do

(*this)(i,j);



回答3:


I also often will do things like this:

grd& This(*this);
This(i,j);

It's just the same as the above examples, but it gets rid of the extra pointer notation and can make the code look cleaner.



来源:https://stackoverflow.com/questions/2085956/c-this-and-operator-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!