我有一个结构:
struct Person{
int scoreone;
int scoretwo;
int scoretotal;
}
main(){
Person a;
a.scoreone=3;
a.scoretwo=5;
//and later
a.scoreone=10;
}
我希望在不使用任何函数的情况下更改 Scoreone 和 Scoretwo 时更新 ScoreTotal。 谢谢
最佳答案
这在 C++ 中是做不到的。处理此问题的 C++ 方法是将 Scoretotal 转换为方法
struct Person{
int scoreone;
int scoretwo;
int scoretotal() { return scoreone + scoretwo; }
};
现在,不再说 person.scoretotal
,而是说 person.scoretotal()
,每次都会重新计算总分。
关于c++ - 在cpp中动态更改属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20143545/