是否可以使用“这个”?在 c++在成员函数中创建本地对象?

发布于 2024-11-29 15:41:05 字数 601 浏览 1 评论 0原文

我有一个关于“this”关键字的问题。我有一个名为“BiPoly”的类,它表示二元多项式。有一个名为 BiPoly::DifferentiateX() 的成员函数,它对 X 进行偏微分,并且它是自我修改的。

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

在另一个名为 BiPoly::eval1() 的成员函数中,我需要获取调用 BiPoly::eval1() 的对象的 DifferentiateX() 结果。由于 DifferentiateX() 是自我修改的,因此我必须创建一个临时变量才能在 eval1() 中获取结果。我的问题是:我可以使用 "this" 在成员函数中创建临时对象吗?如果是这样,我该怎么做?

I have a question regarding "this" keyword. I have a class called "BiPoly", which represents bivariate polynomial. There is a member function 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一笔一画续写前缘 2024-12-06 15:41:05

您可以在 *this 上使用复制构造函数,生成多项式对象的副本,然后对它进行微分和评估:

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

取决于您如何存储系数(例如在标准向量中) ),您甚至可能不需要实际编写复制构造函数。

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.

天涯离梦残月幽梦 2024-12-06 15:41:05

您不应返回对函数内创建的临时对象的引用。它将在函数退出时被销毁。

您宁愿将您的函数声明为这样:

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

注意它返回对象(nv 的副本)但不引用它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文