Frage

I am fairly new to C++ and I have been reading and writing some of my own code. I see these operators from time to time, if that is even the right word to use?

+= // Not sure what it means

So my question is: what do they mean/do, and what are they called?

For further reference, I'd like to know what they are called so I can easily look it up (searching simply for "+=" for instance yielded nothing).

Edit: For anyone else who does not know the meaning (or in my case knew the name of these) I found this Wikipedia link which might come of handy to other people: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

War es hilfreich?

Lösung

Yes, these are operators. More specifically, they are known as compound assignment operators. Here's the full list of them:

*= /= %= += -= >>= <<= &= ^= |=

They are defined like so:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

So x += 5; is almost the same as x = x + 5;.

You can think of it as a modifying addition. If you just do x + 5, the result of the expression is what you get if you add x and 5 together, but x hasn't changed. If you do x += 5;, x actually has 5 added to its value.

Andere Tipps

its just an abbreviation: a+=2; means a=a+2; of course as many operators: you can overload it to give it alternative meaning, ans actually we do it often to provide meaning for example in the case what it means to add int to our class SomeClass:

SomeClass s;
s+=1; //operator+=(SomeClass& s, int i){} is used here

class A{
public:
    A():i_(123){}
    ~A(){}
    int i(){return i_;}
    A const& operator+=(int i){
       std::cout<<"operator+=";
       this->i_=i_+i;
    }
private:
    int i_;
};


int main(int argc, char** argv) {

    A a1;
    a1+=3;
    std::cout<<a1.i();
    return OK;
}

output: operator+=126

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top