我有一个简单的结构,但我不知道如何在该结构中的任何变量发生更改时进行触发的事件/函数调用。在 C# 中,我可以使用 get 和 set 轻松做到这一点,但我如何在 C++ 中做到这一点?
struct Player {
int x = 0;
int y = 0;
bool IsAlive;
float health;
};
当然我可以编写一些自定义类,但我仍然希望像这样轻松更改变量
Player MyPlayer;
MyPlayer.x = 100;
最佳答案
您能做的最好的事情就是代理和重载 operator=
。尽管简单明了的 getter 和 setter 可能工作得更好。
#include <iostream>
using std::cout;
using std::endl;
class Something {
private:
template <typename Type>
class Proxy {
public:
Proxy(Type& in) : data{in} {}
Proxy& operator=(const Type& object) {
cout << "Changed data member" << endl;
this->data = object;
return *this;
}
const Type& operator*() {
return this->data;
}
private:
Type& data;
};
public:
Something(int in) : integer{in} {}
Proxy<int> integer;
};
int main() {
auto something = Something{1};
// trigger code to execute
something.integer = 2;
// getting the value will have a different syntax though
cout << *something.integer << endl;
return 0;
}
关于c++ - 当我的结构中的任何变量发生变化时,有什么方法可以触发事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631713/