program story

C ++에서 func ()와 (* this) .func ()의 차이점

inputbox 2020. 12. 8. 08:02
반응형

C ++에서 func ()와 (* this) .func ()의 차이점


나는 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::ffree 함수를 호출 func하고 두 번째 줄은를 호출 derived::func합니다.


스 니펫에서 알 수는 없지만 라는 두 개의 호출 가능한 객체 가있을 수 있습니다func() . (*this).func();차종은 멤버 함수가 호출되어 있는지.

호출 객체는 A (예를 들어)이 될 수 functor또는 lambda식 :

펑터

struct func_type
{
    void operator()() const { /* do stuff */ }
};

func_type func; // called using func();

람다

auto func = [](){ /* do stuff */ }; // called using func();

예를 들면 :

#include <iostream>

class A
{
public:

    // member 
    void func() { std::cout << "member function" << '\n'; }

    void other()
    {
        // lambda
        auto func = [](){ std::cout << "lambda function" << '\n'; };

        func(); // calls lambda

        (*this).func(); // calls member
    }
};

int main()
{
    A a;
    a.other();
}

산출:

lambda function
member function

이 두 줄이 다른 함수를 호출하는 또 다른 경우 :

#include <iostream>

namespace B
{ void foo() { std::cout << "namespace\n"; } }

struct A { 
  void foo() { std::cout << "member\n"; }

  void bar()
  {
      using B::foo;
      foo();
      (*this).foo();
  }
};

int main () 
{
    A a;
    a.bar();
}

유형 종속 이름을 사용하면 다를 수 있습니다.

void func() { std::cout << "::func()\n"; }

struct S {
    void func() const { std::cout << "S::func()\n"; }
};

template <typename T>
struct C : T
{
    void foo() const {
        func();         // Call ::func
        (*this).func(); // Call S::func
    }
};

데모

참고 URL : https://stackoverflow.com/questions/38764435/difference-between-func-and-this-func-in-c

반응형