转载:什么时候可以不用实例化对象就可以调用类中成员函数

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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值