C ++中func()和(* this).func()之间的区别 [英] Difference between func() and (*this).func() in C++

查看:290
本文介绍了C ++中func()和(* this).func()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++编写其他人的代码,但发现对某个函数 func()的调用很奇怪。例如:

I am working on someone else code in C++, and I found a weird call to a certain function func(). Here is an example:

if(condition)
    func();
else
    (*this).func();

func()有什么区别和(* this).func()

在什么情况下调用 func()(* this).func()会执行不同的代码吗?

What are the cases where the call to func() and (*this).func() will execute different code?

就我而言, func()不是宏。它是基类中的虚函数,在基类和派生类中都有一个实现,并且没有免费的 func() if 位于基类的方法中。

In my case, func() is not a macro. It is a virtual function in the base class, with an implementation in both base and derived class, and no free func(). The if is located in a method in the base class.

推荐答案

实际上是有区别的,但是在非常重要的情况下。考虑以下代码:

There actually is a difference, but in a very non-trivial context. Consider this code:

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;

现在,如果我们调用 tf() test :: f 的第一行将调用自由函数 func ,而第二行将调用 derived :: func

Now, if we call t.f(), the first line of test::f will invoke the free function func, while the second line will call derived::func.

这篇关于C ++中func()和(* this).func()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆