您的位置:首页 > 编程语言 > C语言/C++

静态成员函数如何调用非静态成员变量

2014-03-04 14:16 309 查看
◆函数加参数解决方法

1)、编译时候静态数据和成员函数就有了它的内存区,它不属于类的任何一个具体对象。所以,静态成员函数在编译时候就需要确定x及y的值,而那个时侯变量x,和y还没有创建,所以不可以访问非静态的数据成员。

2)、一般情况下静态成员函数用于访问同一类中的静态数据成员或全局变量,而不访问非静态成员,如需访问非静态成员,需要将对象作为参数,通过对象名访问该对象的非静态成员。

#include <iostream>

using namespace std;

class test

{

public:

      int x,y;

      test(int a=1 , int b=1) { x=a; y=b;}

      static void a(test t) { t.x=t.x+t.y; }

      void print() {cout<<"x="<<x<<endl; cout<<"y="<<y<<endl;}

};

void main()

{

  test t;

  t.print();

  t.a(t);

  t.print();
}

◆函数固定不能加参数解决方法

两种方法解决:

想办法传一个this指针进去或使用全局变量。

1)用全局变量

2)this指针

class CChangeUPSTime

{

public:

       static pascal OSStatus MainWindowEventHandler();

private:

     static CChangeUPSTime *m_pThis;

     WindowRef m_WindowRef;

};

CChangeUPSTime *CChangeUPSTime::m_pThis = NULL;

CChangeUPSTime::CChangeUPSTime()

{

     m_pThis = this;

}

OSStatus CChangeUPSTime::MainWindowEventHandler(){

    m_pThis->m_WindowRef = NULL;



原文地址:http://yaycici.blog.163.com/blog/static/173759063201291741815353/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ vc MFC