如何使变量始终等于某些计算的结果? [英] How can I make a variable always equal to the result of some calculations?

查看:48
本文介绍了如何使变量始终等于某些计算的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数学上,如果 z = x + y / 2 ,那么只要我们替换了< x y 的值。每当我们更改 x 和<$ c $的值时,是否可以在编程中做到这一点而不必专门更新 z c> y ?

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?

我的意思是这样的东西行不通,对吧?

I mean something like that won't work, right?

int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;

如果您对我为什么需要它感到困惑,我希望显示该变量,并在出现以下情况时自动更新该变量

If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.

就像杀死一条小怪并获得金币一样,其净值(现金+自己物品的价值)也会发生变化。还是汽车的速度计会根据您驾驶的速度或速度而变化。

Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.

推荐答案

编辑:在我完全按照要求回答问题时,请查看 Artelius 'answer 。它解决了我的答案没有解决的一些问题(封装,避免重复,引用不可靠的风险)。 Jonathan Mee 答案

While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.

您的意思是这样的:

class Z
{
    int& x;
    int& y;
public:
    Z(int& x, int& y) : x(x), y(y) { }
    operator int() { return x + y; }
};

该类将结果的计算延迟到强制转换为int为止。由于强制转换运算符不是显式的,因此只要需要int即可使用 Z 。由于int有 operator<< 的重载,因此可以将其与e一起使用。 G。 std :: cout 直接:

The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:

int x, y;
Z z(x, y);
std::cin >> x >> y;
if(std::cin) // otherwise, IO error! (e. g. bad user input)
    std::cout << z << std::endl;

请注意,仍然有 still 函数调用(隐式即使其中不可见,也可以使用强制转换操作符之一)。实际上,运算符进行了一些真实的计算(而不是仅访问内部成员),因此,隐藏函数调用是否真的是个好主意还是值得怀疑的。

Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...

这篇关于如何使变量始终等于某些计算的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆