我想跟踪特定成员变量何时更改值,以便我可以将其打印出来。现在,明显的解决方案是在成员的Set
方法中添加跟踪功能,如下所示:
class Foo
{
public:
Foo() {}
void SetBar(int value)
{
//Log that m_bar is going to be changed
m_bar = value;
}
private:
int m_bar; // the variable we want to track
};
我面临的问题是我正在处理一个庞大的项目,有些类有很多方法可以在内部更改成员变量,而不是调用他们的Set
个。
m_bar = somevalue;
而不是:
SetBar(somevalue);
因此,我想知道是否有更快/更干净的方法来实现我想要的,而不仅仅是将每个m_bar =
更改为SetBar(
。赋值运算符可能仅为该成员变量重载?
答案 0 :(得分:4)
如果您可以更改成员的数据类型,则可以将其更改为记录器类型。
示例:
#include <iostream>
template <class T>
class Logger
{
T value;
public:
T& operator=(const T& other)
{
std::cout << "Setting new value\n";
value = other;
return value;
}
operator T() const
{
return value;
}
};
class Foo
{
public:
Foo() {}
void SetBar(int value)
{
//Log that m_bar is going to be changed
m_bar = value;
}
private:
#if 1
Logger<int> m_bar; // the variable we want to track
#else
int m_bar; // the variable we want to track
#endif
};
int main()
{
auto f = Foo();
f.SetBar(12);
}
ideone的在线示例。