类中的静态成员函数访问非静态成员变量



类中的静态成员函数访问非静态成员变量



1.思路:

静态成员函数属于类(通过类访问,调用函数时没有提供this指针),
非静态成员函数属于实例(通过对象访问)(默认都提供了this指针),
非静态成员也属于实例(通过对象访问),
所以,要想在静态成员函数访问非静态成员变量,
无非就是实例化一个对象,然后通过对象访问非静态成员变量。



2.实现方法

第一种:类外实例化对象,传参数(看自己需要使用值、地址、引用)

class Test
{
public:
       Test() {  }
       ~Test(){  }
      void static testFun(Test& test);

private:
      int m_a;


};


     void Test::testFun(Test& test)
    {
          test.m_a=20;
   }







第二种:类外实例化对象,全局对象

Test test;


class Test
{
public:
       Test(){  }
       ~Test(){   }
       void static testFun();

private:
       int m_a;


};


     void Test::testFun()
    {
           test.m_a=20;
     }








第三种:类中实例化对象,在创建的时候把this指针赋值给那个静态成员

#include<stdio.h>
#include<string.h>


class Test
{
public:
       Test() {   test = this ; }
       ~Test(){  }
       void static testFun();
       void printMember();

private:
     int m_a;
    static Test* test;


};
   Test* Test::test;                        //静态成员需要初始化


    void Test::testFun()
    {
          test->m_a=20;           
    }


     void Test::printMember()
    {
         printf("%d\n", this->m_a); 
   }


    int main()
   {
        Test test1;
        Test::testFun();
         test1.printMember();             //输出20, 成功改变成员变量m_a的值


     return 0;
   }



单实例



#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>



#include<stdio.h>  
#include<string.h>  
  
  
class Test  
{  
private:
	Test() {  };
public:  
       static Test* getTest() {   
		   static Test instance;  
		   test = &instance ;
		   return &instance;}  
       ~Test(){ printf("sdg\n"); }  
       void static testFun();  
       void printMember();  
  
private:  
     int m_a;  
    static Test* test;  
  
  
};  
Test* Test::test;                        //静态成员需要初始化  
  
  
    void Test::testFun()  
    {  
          test->m_a=20;             
    }  
  
  
     void Test::printMember()  
    {  
         printf("%d\n", this->m_a);   
   }  
  
  
    int main()  
   {  
        Test* test1 = Test::getTest();  
        Test* test2 = Test::getTest();  
        Test::testFun();  
        test1->printMember();             //输出20, 成功改变成员变量m_a的值  
	test2->printMember();             //输出20, 成功改变成员变量m_a的值  
  
  
     return 0;  
   }  





  • 11
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值