本文共 1666 字,大约阅读时间需要 5 分钟。
http://blog.csdn.net/u011857683/article/details/52294353
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();
-
-
- 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();
- test2->printMember();
-
-
- return 0;
- }