轨道成员变量值更改
Track member variable value change
我想跟踪特定成员变量何时更改值,以便打印出来。现在,显而易见的解决方案是在成员的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
ter。
m_bar = somevalue;
代替:
SetBar(somevalue);
所以我想知道是否有一种更快/更干净的方法可以实现我想要的,而不仅仅是将每个m_bar =
更改为SetBar(
。赋值运算符可能只为该成员变量重载?
如果可以更改成员的数据类型,则可以将其更改为记录器类型。
示例:
#include <iostream>
template <class T>
class Logger
{
T value;
public:
T& operator=(const T& other)
{
std::cout << "Setting new valuen";
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的在线示例。
相关文章:
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 获取模板参数的成员变量值列表
- 使用特定成员变量值创建类型的类型
- 对象在将操作推送到向量后成员变量值已更改
- 根据C 中的变量值创建成员函数
- 初始化静态成员变量值的正确位置
- 观察成员变量值的变化
- C++ 成员变量值根据是否打印出来而变化
- 轨道成员变量值更改
- 为什么我的析构函数没有破坏我的对象,它仍然保留其成员变量值
- C++当我离开默认构造函数时,我的初始化字符串消失了,但我的其他成员变量值没有