开发者

Modify an object without using it as parameter

I have a global object "X" and a class "A". I need a function F in A which have the ability to modify the content of X.

For some reason, X cannot be a data member of A (but A can contain some member Y as reference of X), and also, F cannot have any parameter, so I cannot pass X as an parameter into F. (Here A is an dialog and F is a slot without any parameter, such as accept() )

How can I modify X within F if I cannot pass X int开发者_运维百科o it? Is there any way to let A know that "X" is the object it need to modify?? I try to add something such as SetItem to specify X in A, but failed.


If you don't want F to reference X globally, then you could 'set' it on the object before calling the "worker" method. E.g.

class A
{
public:
   A() : member_x(NULL) { }
   void SetX(X* an_x) { member_x = an_x; }
   void F(); { member_x->Manipulate(); }

private:
   X* member_x;
};

X global_x;
A global_a;

void DoStuff()
{
   global_a.SetX(&global_x);
   global_a.F();
}


Since X is a global object you should be able to access it from A::F().
For example:

In B.h:

class B
{
public: 
  B(){x=1};
  virtual ~B(){}
  ChangeSomething(){x=2;}
private:
  int x;
};

In main.cpp

#include "A.h"
#include "B.h"

B X;

int main( int argc, const char* argv[] )
{
  A instanceOfA;
  instanceOfA.ModifyGlobalObject();
}

in A.h

#include "B.h"
extern B X;
class A
{
public:
  ModifyGlobalObject(){X.ChangeSomething();}
};

Of course these classes and global variables can be in different files if you include the headers correctly.


If X is global, you can set it it within the A::F function.

extern X

class A
{
   void F()
   {
        // set the global variable X
        X = someValue;
   }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜