从 C++ 中同一类的另一个成员函数调用成员函数,目标 C
考虑以下问题:
class A{
//data members
void foo()
{
bar();//is this possible? or should you say this->bar() note that bar is not static
}
void bar()
{
}
}//end of class A
如何从另一个函数中调用成员函数?静态函数如何影响“this”的使用。 应该在对象上调用函数吗?
Consider the following:
class A{
//data members
void foo()
{
bar();//is this possible? or should you say this->bar() note that bar is not static
}
void bar()
{
}
}//end of class A
How do you call member functions from within another? And how does static functions affect the use of 'this'.
Should functions be called on an object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
纳瓦兹是正确的:“这个”是隐含的。一个例外是 foo 是静态函数,因为在静态函数中没有“this”。在这种情况下,你不能使用 bar() ,除非 bar() 也是一个静态函数,并且你根本不能使用 this->bar() 。
Nawaz is correct: 'this' is implicit. The one exception is if foo were a static function, because in static functions there is no 'this'. In that case, you can't use bar() unless bar() is also a static function, and you can't use this->bar() at all.
this
是隐式的。所以两者是等价的。您可以使用其中任何一个。但后来我想,如果只是bar()
就足够了,那为什么还要使用this->bar()
呢?仅当存在一些歧义时才使用
this
,否则使用更简单的!this
is implicit. So both of them are equivalent. You can use any of them. But then I think, if justbar()
is enough, then why usethis->bar()
?Use
this
only when there is some ambiguity, otherwise use the simpler one!