是否可以使用“这个”?在 c++在成员函数中创建本地对象?
我有一个关于“this”关键字的问题。我有一个名为“BiPoly”的类,它表示二元多项式。有一个名为 BiPoly
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() 的成员函数中,我需要获取调用 BiPolyDifferentiateX()
结果。由于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
*this
上使用复制构造函数,生成多项式对象的副本,然后对它进行微分和评估:取决于您如何存储系数(例如在标准
向量
中) ),您甚至可能不需要实际编写复制构造函数。You can use copy constructor on
*this
, yielding a copy of your polynomial object which you then differentiate and evaluate:Depending on how do you store the coefficients (e.g. in standard
vector
), you might not even need to actually write the copy constructor.您不应返回对函数内创建的临时对象的引用。它将在函数退出时被销毁。
您宁愿将您的函数声明为这样:
注意它返回对象(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:
Note it returns object (copy of nv) but not reference to it.