我要创建一个类/结构,其中一个属性在功能上依赖于其他属性。如何做到这一点?
struct Numbers {
int a;
int b;
int c; // c == a+b
}
Numbers n1 {1, 2, 3}; // Ok.
Numbers n2 {1, 2, 4}; // Error!
In my use case, a, b, c
are constant, if that matters (so const int
may be used).
All attributes will appear many times in class/struct methods, so the goal is to cache the value a+b
. Addition is used as an example, the dependency function may be more complex.
If
a
andb
are mutable then you can't enforce thatc
is kept in sync; all three would have to be const for you to enforce this invariant.The simplest approach would be to make
c
a function:If you want the value of
c
to be cached instead of computed when needed then you need to hidea
andb
behind accessors as well so that you can updatec
when they are updated.您可以执行以下操作: