zoukankan      html  css  js  c++  java
  • 转载:什么时候可以不用实例化对象就可以调用类中成员函数

    http://blog.csdn.net/dwb1015/article/details/32933349

    对于一个类A,对于这个定义((A*)0)或者 A *p = NULL 都可以调用类中的那些成员函数。

            第一种情况:非静态成员函数没有使用类的非静态数据成员,调用的其他非静态成员函数也不能使用类的非静态数据成员

    [cpp] view plain copy
     
     print?
    1. #include <iostream>  
    2.   
    3. using namespace std;  
    4.   
    5. class A  
    6. {  
    7. public:  
    8.     void fun1()  
    9.     {  
    10.         cout<<"fun1"<<endl;  
    11.   
    12.         fun2();  //如果fun2函数内部调用了数据成员a,则会调用失败  
    13.     }  
    14.   
    15.     void fun2()  
    16.     {  
    17.         cout<<"fun2"<<endl;  
    18.         //a = 1;  
    19.     }  
    20.   
    21. private:  
    22.     int a;  
    23.     int b;  
    24. };  
    25.   
    26.   
    27. int main()  
    28. {  
    29.     A *p = NULL;  
    30.     p->fun1();  
    31. }  

           第二种情况:非静态成员调用类的静态数据成员。

    [cpp] view plain copy
     
     print?
    1. #include <iostream>  
    2.   
    3. using namespace std;  
    4.   
    5. class A  
    6. {  
    7. public:  
    8.     void fun1()  
    9.     {  
    10.         cout<<"fun1"<<endl;  
    11.         a = 3;  
    12.         cout<<"a = "<<a<<endl;  
    13.     }  
    14.   
    15. private:  
    16.     static int a;  
    17.     int b;  
    18. };  
    19.   
    20. int A::a = 0;  
    21.   
    22.   
    23. int main()  
    24. {  
    25.     A *p = NULL;  
    26.     p->fun1();  
    27. }  


     

            第三种情况:类的静态成员函数

    [cpp] view plain copy
     
     print?
      1. #include <iostream>  
      2.   
      3. using namespace std;  
      4.   
      5. class A  
      6. {  
      7. public:  
      8.     static void fun1()  
      9.     {  
      10.         cout<<"fun1"<<endl;  
      11.         a = 3;  
      12.         cout<<"a = "<<a<<endl;  
      13.     }  
      14.   
      15. private:  
      16.     static int a;  
      17.     int b;  
      18. };  
      19.   
      20. int A::a = 0;  
      21.   
      22.   
      23. int main()  
      24. {  
      25.     A *p = NULL;  
      26.     p->fun1();  
      27. }  
  • 相关阅读:
    【2019-12-13】泛型
    【2019-12-12】函数
    【2019-12-10】类
    【2019-12-05】接口
    【2019-12-3】变量声明
    【2019-11-24】基础类型
    【2019-11-20】服务与DI简介
    【2019-11-20】组件简介
    android之ListView与Adapter(结合JavaBean)
    android基类Adapter
  • 原文地址:https://www.cnblogs.com/penghuster/p/7070586.html
Copyright © 2011-2022 走看看