我正在使用C ++编写其他人的代码,但发现对某个函数的调用很奇怪func()
。这是一个例子:
if(condition)
func();
else
(*this).func();
func()
和之间有什么区别(*this).func()
?
在什么情况下,对func()
和的调用(*this).func()
将执行不同的代码?
就我而言,func()
不是宏。它是基类中的虚函数,在基类和派生类中都有一个实现,并且没有free func()
。在if
位于在基类的方法。
实际上是有区别的,但是在非常重要的情况下。考虑以下代码:
void func ( )
{
std::cout << "Free function" << std::endl;
}
template <typename Derived>
struct test : Derived
{
void f ( )
{
func(); // 1
this->func(); // 2
}
};
struct derived
{
void func ( )
{
std::cout << "Method" << std::endl;
}
};
test<derived> t;
现在,如果我们调用t.f()
,第一行将test::f
调用free函数func
,而第二行将调用derived::func
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句