从 C++ 中同一类的另一个成员函数中调用成员函数,目标 C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4930309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling member functions from within another member function of the same class in C++, objective C
提问by Namratha
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?
你如何从另一个内部调用成员函数?静态函数如何影响“this”的使用。应该在对象上调用函数吗?
回答by Ens
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.
Nawaz 是正确的:'this' 是隐含的。一个例外是如果 foo 是一个静态函数,因为在静态函数中没有“this”。在这种情况下,除非 bar() 也是一个静态函数,否则您不能使用 bar(),并且您根本不能使用 this->bar()。
回答by Nawaz
bar();//is this possible? or should you say this->bar()
this
is implicit. So both of them are equivalent. You can use any of them. But then I think, if just bar()
is enough, then why use this->bar()
?
this
是隐含的。所以两者是等价的。您可以使用其中任何一个。但后来我想,如果就bar()
足够了,那为什么要使用this->bar()
?
Use this
only when there is some ambiguity, otherwise use the simpler one!
使用this
时,才会有一些歧义,否则使用更简单的一个!