📜  C ++中“this”指针的类型

📅  最后修改于: 2022-05-13 01:54:21.651000             🧑  作者: Mango

C ++中“this”指针的类型

this 指针指向类的当前对象,并将其作为参数传递给另一个方法。在 C++ 中,此指针作为隐藏参数传递给所有非静态成员函数调用。

“this”指针的类型:this 的类型取决于函数声明。此指针的类型是const ExampleClass *ExampleClass *。这取决于它是否位于类ExampleClassconst或非 const方法中。

1)如果类 X 的成员函数声明为const ,则 this 的类型为const X*如下图,

CPP
// CPP Program to demonstrate
// if the member function of a
// class X is declared const
#include 
using namespace std;
  
class X {
    void fun() const
    {
        // this is passed as hidden argument to fun().
        // Type of this is const X* const
    }
};


CPP
// CPP Program to demonstrate
// if the member function is
// declared volatile
#include 
using namespace std;
  
class X {
    void fun() volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is volatile X* const
    }
};


CPP
// CPP program to demonstrate
// if the member function is
// declared const volatile
#include 
using namespace std;
  
class X {
    void fun() const volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is const volatile X* const
    }
};


2)如果成员函数声明为volatile,则this的类型为volatile X* ,如下图,

CPP

// CPP Program to demonstrate
// if the member function is
// declared volatile
#include 
using namespace std;
  
class X {
    void fun() volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is volatile X* const
    }
};

3)如果成员函数声明为const volatile ,则 this 的类型为const volatile X*如下图,

CPP

// CPP program to demonstrate
// if the member function is
// declared const volatile
#include 
using namespace std;
  
class X {
    void fun() const volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is const volatile X* const
    }
};

请注意constvolatileconst volatile是类型限定符。