我想跟踪特定成员变量何时更改值,以便可以将其打印出来。现在,明显的解决方案是在成员的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
};
Run Code Online (Sandbox Code Playgroud)
我面临的问题是我正在开发一个大型项目,并且某些类具有许多内部更改成员变量而不是调用其Setter的方法。
m_bar = somevalue;
Run Code Online (Sandbox Code Playgroud)
代替 :
SetBar(somevalue);
Run Code Online (Sandbox Code Playgroud)
所以我想知道是否有一种更快/更干净的方法来实现我想要的,而不是仅仅将每个更改m_bar =为SetBar(。赋值运算符可能仅对该成员变量重载?
如果您可以更改成员的数据类型,则可以将其更改为记录器类型。
例子:
#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);
}
Run Code Online (Sandbox Code Playgroud)
ideone 的在线示例。