0

C++ での複合代入を学習するために、次のコードを作成して、それらが何を行うかを示します。

int b05;
int b06 = 13;

b05 = 49;
b05 += b06; // b05 = b05 + b06
cout << "(+=) compound assignment: " << b05 << endl;

b05 = 49;
b05 -= b06; // b05 = b05 - b06
cout << "(-=) compound assignment: " << b05 << endl;

b05 = 49;
b05 *= b06; // b05 = b05 * b06
cout << "(*=) compound assignment: " << b05 << endl;

b05 = 49;
b05 /= b06; // b05 = b05 / b06
cout << "(/=) compound assignment: " << b05 << endl;

b05 = 49;
b05 %= b06; // b05 = b05 % b06
cout << "(%=) compound assignment: " << b05 << endl;

b05 = 49;
b05 >>= b06; // b05 = b05 >> b06
cout << "(>>=) compound assignment: " << b05 << endl;

b05 = 49;
b05 <<= b06; // b05 = b05 << b06
cout << "(<<=) compound assignment: " << b05 << endl;

b05 = 49;
b05 &= b06; // b05 = b05 & b06
cout << "(&=) compound assignment: " << b05 << endl;

b05 = 49;
b05 ^= b06; // b05 = b05 ^ b06
cout << "(^=) compound assignment: " << b05 << endl;

b05 = 49;
b05 |= b06; // b05 = b05 | b06
cout << "(|=) compound assignment: " << b05 << endl;

ご覧のとおりb05、前の操作で値が変更されたため、値 49 を に再割り当てする必要があります。

これを回避する方法はありますか?または、同じ出力を達成するためのより効率的な方法はありますか? (コード例をいただければ幸いです)

4

4 に答える 4

2

マクロを使用すると、次のようなことができます。

#define compound(op) \
    b05 = 49; \
    b05 op b06; \
    std::cout << "(" << #op << ") compound assignment: " << b05 << std::endl;

次に、次のように呼び出します。

int b05, b06 = 13;

compound(+=)
compound(/=)
// etc...

これが実際に行うことは、コンパイル時のテキスト置換です。があるすべての場所compound(...)で、複合マクロのテキストにop置き換えられ、括弧内に指定したもの (この場合は何らかの演算子) に置き換えられます。

これを実際に実行するg++ -E <codefile>と、マクロ (およびすべてのインクルード) が展開されていることがわかります。

于 2016-08-08T22:57:22.423 に答える
1

複合操作を誤解しています。それらは式の左の値にのみ影響します。

#include <iostream>

int main() {
    int b05 = 10; int b06 = 5;
    b05 |= b06;
    std::cout << "b05 " << b05 << ", b06 " << b06 << "\n";
}

http://ideone.com/5nT7pR

出力:

b05 15, b06 5

b06 は変更されていません。

于 2016-08-08T22:57:19.470 に答える
0

たぶん、次のような関数を作成できます。

class Obj
{
public:
    Obj& operator+= (const Obj &) { return *this; }
    Obj& operator-= (const Obj &) { return *this; }
};

void testFunction(std::function<Obj&(Obj *, const Obj &)> functionToTest)
{
  Object object;
  Object otherObject;
  functionToTest(&object, otherObject);
  cout << "(+=) function test: " << object << endl;
}

int main(void)
{
  std::function<Obj&(Obj *, const Obj &)> functionToTest(&Obj::operator+=);
  testFunction(functionToTest);

  std::function<Obj&(Obj *, const Obj &)> functionToTest2(&Obj::operator-=);
  testFunction(functionToTest2);
}

このコードは 100% 正しいわけではありませんが、アイデアが得られるはずです。原則は適切です。もちろん、プリミティブ型では機能しません。

于 2016-08-08T23:34:15.667 に答える