我需要将我正在处理的类的对象传递给函数。对我来说很难解释,所以我做了一个简单的例子。
我尝试使用“this”运算符,希望它将“this”对象发送到函数,但没有用。我也试过谷歌搜索这个问题,但我找不到任何合理的答案。
#include <iostream>
unsing namespace std;
class apple;
int eatApple(apple & a)
{
a.var1=0;
a.var2=0;
return 0;
}
class apple
{
int var1;
int var2;
void cutApple();
};
void apple::cutApple()
{
var1/=2;
var2/=2;
eatApple(/*HERE I HAVE TO PASS THE OBJECT OF THE CLASS TO THE FUNCTION*/);
}
int main()
{
apple Apple;
Apple.cutApple();
return 0;
}
请注意,此代码只是问题的一个示例。我在 /* */ 中写的地方,那是我尝试“this”运算符的地方,但我没有工作。
函数头看起来像这样:int eatApple(apple & a)
,这意味着它接受对 的引用apple
。this
始终是一个指针(不是引用),因此您需要取消引用它:
eatApple(*this);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句