假设我有两个类:
A 类:
class A
{
private:
int _i;
public:
A(int i){_i=i;}
void update(int t){_i=t;}
friend class B;
};
B 类:
class B
{
private:
A &_a;
public:
void respond();
B(A &);
};
B::B(A & a)
:_a(a)
{}
void
B::respond()
{
/*
if (a._i has been updated after last call of B::respond)
{
do something
}
else
{
do nothing
}
*/
}
有没有办法在 C++/C++11 中实现 B::respond()
中描述的任务? _i
被指针替换,B::respond()
需要响应指针的内容怎么办?
请注意,我无法修改类 A
。
最佳答案
有两种方法可以实现:
- 在
B::respond()
函数中保存a._i
的值,并在下一个B::respond() 中与该值进行比较
调用。 - 在调用
A::update
时设置一些内部标志。调用B::respond()
时,检查该标志并将其取消设置。
关于c++ - C++ 类函数能否判断自上次调用以来类成员对外部类的引用是否已更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349130/