开发者

Is it possible to use "this" in c++ to create local object in member function?

I have a question regarding "this" keyword. I have a class called "BiPoly", which represents bivariate polynomial. There is a member functio开发者_运维知识库n called BiPoly<NT>::DifferentiateX(), which gets Partial Differentiation wrt X, and it's self-modified.

template <class NT>
BiPoly<NT> & BiPoly<NT>::differentiateX() { 
    if (ydeg >= 0)
      for (int i=0; i<=ydeg; i++) 
    coeffX[i].differentiate();

    return *this;
}//partial differentiation wrt X

In another member function called BiPoly::eval1(), I need to get the result of DifferentiateX() of the object who calls BiPoly<NT>::eval1(). Since DifferentiateX() is self-modified, I have to create a temp variable to get the result within eval1(). My question is: can I use "this" to create a temp object within member function? If so, how do I do that?


You can use copy constructor on *this, yielding a copy of your polynomial object which you then differentiate and evaluate:

BiPoly<NT> copy(*this);
copy.DifferentiateX();
NT val = copy.eval1(arg);

Depending on how do you store the coefficients (e.g. in standard vector), you might not even need to actually write the copy constructor.


You should not return reference to temporary object that was created inside your function. It will be destroyed on function exit.

You'd rather declare your function as this:

template <class NT>
BiPoly<NT> BiPoly<NT>::differentiateX() { 
    BiPoly nv = *this;     
    if (nv.ydeg >= 0)
      for (int i=0; i<=nv.ydeg; i++) 
    nv.coeffX[i].differentiate();

    return nv;
}//partial differentiation wrt X

Note it returns object (copy of nv) but not reference to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜