开发者

How to pass a linc to class function and call it?

开发者 https://www.devze.com 2023-02-04 04:56 出处:网络
So I have a class like class mySafeData { public: void Set( int i ) { myMutex.lock(); myData = i; myMutex.unlock();

So I have a class like

class mySafeData
{
public:
    void Set( int i ) 
    {
        myMutex.lock();
        myData = i;
        myMutex.unlock();
    }
    void Get( int& i)
    {
        myMutex.lock();
        i = myData;
        myMutex.unlock();
    }
private:
    int myData;
    boost::mutex myMutex;

};

its instance is running. Lets call instance A. I want to create a new class that would take as a start up argument some kind of link to Getter from A and woul开发者_开发知识库d be capable to somehow save link to thet getter for calling it inside its private methods vhen needed. how to do such thing?


Sounds like you want something like this:

class myOtherData
{
public:
    myOtherData(mySafeData& dataSource) :
    myDataSource(&dataSource)
    {}

private:
    // note that if you take the advice in the comments,
    // you don't need this wrapper function at all,
    // it's simple just to call myDataSource.Get()
    int GetData()
    {
        int result;
        myDataSource.Get(result);

        return result;
    }

    mySafeData* myDataSource;
};

mySafeData a;
myOtherData b(a);

// b uses a as its data source (make sure it lives as long!)


I'm not sure what you mean by linc/link. Are you asking for anything more than this pattern?

class Foo {
public:
    Foo(mySafeData& d) : data(d) {}

    int someFunction() {
        int i;
        data.get(i);
        return i;
    }
private:
    mySafeData& data;
};

...
Foo f(a);


What's wrong with pointers? Smart, Shared, Scoped... I'll use standard pointers for now.

class B
{
public:
  B(mySafeData* ptr) // constructor takes a memory pointer as parameter
  :SafeData_ptr(ptr)
  { 
     SafeData_ptr->foo(); // call public function from class A
  }

  ~B() // destructor
  {
  }

private:
  mySafeData* SafeData_ptr; // will hold the mem address of instance A when
                            // this class is initialized
};

Later on your code, when you have instance A ready, you would do something like this:

B b_demo(&A); // &A passes the memory address of the instantiated object
              // and A::foo() will be automatically called when B is constructed.

This is probably not the smartest way to do it, but I think it illustrates the idea.

0

精彩评论

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