zoukankan      html  css  js  c++  java
  • 空类指针为什么可以调用类的成员函数 以及 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;
    }
    
    新战场:https://blog.csdn.net/Stephen___Qin
  • 相关阅读:
    手机号码 正则表达式
    邮政编码的正则表达式
    对象为null,调用非静态方法产生空指针异常
    文件找不到异常(FileNotFoundException)
    数组下标越界异常解决方法
    空指针异常的解决方法
    需求:打印九九乘法表
    创建简单线程
    ·博客作业06--图
    博客作业05--查找
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/9219853.html
Copyright © 2011-2022 走看看