当我的结构中的任何变量发生变化时,有什么方法可以触发事件?

时间:2017-06-19 13:18:29

标签: c++ events visual-c++ struct

我有一个简单的结构,但我不知道在这个结构的任何变量发生变化时触发事件/函数调用。在C#中,我可以通过get和set轻松完成,但我在C ++中的表现如何?

struct Player {
    int x = 0;
    int y = 0;
    bool IsAlive;
    float health;
};

当然我可以编写一些自定义类,但我仍然希望像这样轻松更改变量

Player MyPlayer;
MyPlayer.x = 100;

1 个答案:

答案 0 :(得分:1)

The best you can do is a proxy and overload operator=. Although plain and simple getters and setters might work better.

#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;
}