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
  • 相关阅读:
    leetcode100
    leetcode237
    leetcode171
    leetcode122
    leetcode387
    2018-8-10-win10-uwp-如何打包Nuget给其他人
    2018-8-10-win10-uwp-如何打包Nuget给其他人
    2019-11-13-如何在国内发布-UWP-应用
    2019-11-13-如何在国内发布-UWP-应用
    2019-2-21-PowerShell-通过-WMI-获取设备厂商
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/9219853.html
Copyright © 2011-2022 走看看