空类指针为什么可以调用类的成员函数 以及 A(){}和A();

1. 代码及问题

#include <iostream>
using namespace std;

class A
{
public:
    A() {}        //A *p = new A()时:此时A须写成A() {}
    void hello()
    {
        std::cout << "hello" << std::endl;
    }
};

int main()
{
    A *p = new A();
    p = NULL;
    p->hello(); //空类指针为什么可以调用类的成员函数 ?
    return 0;
}

2.论坛里的解答

观点A:

p->hello();执行的时候,hello接收的this指针就是p(即NULL),但hello方法没有用到this指针,所以不会出错

观点B:

因为你的成员函数里面 没有使用this指针

class test
{
public:
test(){}
void hello(){a = 1;} //这个函数就不能调用了,这里实际上是 this->a = 1;
int a;
};

观点C:

当实例指针delete或指空后,只要没使用到this,都没事的

想想内存的存放,就知道了

class编译的时候,函数是在全局代码区,new一个实例是在堆上(被置空或delete),指针调用函数(代码区),由于没使用到this(在堆上)所以正常运行

3. 自己衍生的问题

#include <iostream>
using namespace std;

class A
{
public:
    A();    //A *p时:此时A可以写成A();  A(){}和A();的区别在哪呢
    void hello()
    {
        std::cout << "hello" << std::endl;
    }
};

int main()
{
    A *p;
    p = NULL;
    p->hello()
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Stephen-Qin/p/9219853.html