1

次の表現について簡単な質問があります。

int a_variable = 0;
if(0!=a_variable)
   a_variable=1;

(0 != a_variable)" " と " "はどう違い(a_variable != 0)ますか? 今のところエラーはありませんが、これは間違った使い方ですか??

4

3 に答える 3

2

を忘れると!、最初のエラーが発生(0 = a_variable)し、2番目のエラーが発生します(a_variable = 0)

また、ユーザー定義の演算子を使用すると、2番目の形式はメンバー関数を使用して実装できますが、最初の形式は非メンバー(おそらくフレンド)関数のみにすることができます。そして、本当に悪い考えですが、2つの形式を異なる方法で定義することは可能です。もちろん、それ以降a_variableintこの例では有効なユーザー定義の演算子はありません。

于 2010-07-27T19:20:36.987 に答える
-1

0 != xとの間に違いはありませんx != 0

于 2010-07-27T19:20:56.783 に答える
-1

Any difference it may make is the order in which the arguments will be evaluated. a != b would conventionally evaluate a, then evaluate b and compare them, while b != a would do it the other way round. However, I heard somewhere that the order of evaluation is undefined in some cases.

It doesn't make a big difference with variables or numbers (unless the variable is a class with overloaded != operator), but it may make a difference when you're comparing results of some function calls.

Consider

int x = 1;
int f() {
  x = -1;
  return x;
}
int g() {
  return x;
}

Assuming the operands are evaluated from left to right, then calling (f() != g()) would yield false, because f() will evalute to -1 and g() to -1 - while (g() != f()) would yield true, because g() will evaluate to 1 and f() - to -1.

This is just an example - better avoid writing such code in real life!

于 2010-07-27T19:28:04.930 に答える