类对象指针为NULL值也可以调用类的方法

#include <iostream>
#include 
<stdexcept>

struct X
{
    
void Method(){std::cout<<"method\n";}
};
int main() 
{

    X 
*p=NULL;
    
try
    {
        p
->Method();
    }
    
catch(std::exception& e)
    {
        std::cout
<<"exception\n";
    }
    system(
"PAUSE");
    
return 0;
}

这段代码会输出method而不是exception。

因为类的成员方法只是隐藏了第一个参数为类的对象实例的指针——this的普通函数。

在method方法中并没有使用this指针,因此它可以被正确调用。

原文地址:https://www.cnblogs.com/mumuliang/p/2085038.html