03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

86 CHAPTER 3. CLASSES<br />

of the decrement/increment we have the same symbol <strong>for</strong> two operators respectively that are<br />

distinguished by the position.<br />

To make a long story short, if we write i++ we must define the postfix increment:<br />

single index operator++ (int)<br />

{<br />

single index tmp(∗this);<br />

++i1;<br />

return tmp;<br />

}<br />

We see that the operation requires an extra copy. The object itself must be incremented but<br />

the returned valued must be still the old one. If we returned the object itself, i.e. ∗this, then we<br />

had no possibility to increment it after the return. There<strong>for</strong>e we need a copy be<strong>for</strong>e we modify<br />

the object. Alternatively we could omit the copy and return a new object with the old value:<br />

single index operator++ (int)<br />

{<br />

++i1;<br />

return single index(i1 − 1);<br />

}<br />

This avoids the copy at the beginning but we still create a new object. These implementations<br />

show that the postfix operators are somewhat more expensive than prefix operators; and this<br />

true <strong>for</strong> all user-defined types. For C ++-own types the compiler can generate efficient executables<br />

<strong>for</strong> both <strong>for</strong>ms.<br />

The really sad part of the story is that we put so much ef<strong>for</strong>t returning the old value of our<br />

index and does not even use it. There<strong>for</strong>e, we give the following<br />

Advise<br />

If you increment or decrement user-defined types prefer the prefix notation,<br />

especially if the value of the changed variable is not used in the statement.<br />

In the examples, we declared both indices as single index. It is sufficient doing this <strong>for</strong> the first<br />

one and let the implicit constructor convert the second one:<br />

A[single index(0), 1]<br />

Un<strong>for</strong>tunately, we cannot write<br />

A[0, 1]<br />

The compiler will give an error message 11 like:<br />

no match <strong>for</strong> ≫operator[]≪ in ≫A[(0, 0)]≪<br />

To call operator[], the compiler would need to per<strong>for</strong>m multiple steps that depend on each other:<br />

first the zeros that are considered int would need to be converted to single index and then the<br />

11 This is the message from GNU compiler.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!