所以我有一个像
这样的课程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;
};
它的实例正在运行。让我们调用实例A.我想创建一个新的类,它可以作为一个启动参数从Get中获取某种类型的Getter链接,并且能够以某种方式保存到gett的链接,以便在需要的私有方法中调用它。该怎么办?
答案 0 :(得分:2)
听起来你想要这样的东西:
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!)
答案 1 :(得分:1)
我不确定你的意思是linc / link。你要求的不仅仅是这种模式吗?
class Foo {
public:
Foo(mySafeData& d) : data(d) {}
int someFunction() {
int i;
data.get(i);
return i;
}
private:
mySafeData& data;
};
...
Foo f(a);
答案 2 :(得分:1)
指针有什么问题? Smart,Shared,Scoped ......我现在将使用标准指针。
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
};
稍后您的代码,当您准备好实例A时,您将执行以下操作:
B b_demo(&A); // &A passes the memory address of the instantiated object
// and A::foo() will be automatically called when B is constructed.
这可能不是最聪明的方法,但我认为这说明了这个想法。