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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

80 CHAPTER 3. CLASSES<br />

One could not even write a loop over all elements.<br />

To enable such iteration, we need a function like:<br />

class vector<br />

{<br />

public:<br />

double at(int i)<br />

{<br />

assert(i >= 0 && i < my size);<br />

return data[i];<br />

}<br />

};<br />

Summing the entries of vector v reads:<br />

double sum= 0.0;<br />

<strong>for</strong> (int i= 0; i < v.size(); i++)<br />

sum+= v.at(i);<br />

C ++ and C access entries of (fixed-size) arrays with the subscript operator. It is, thus, only<br />

natural doing the same <strong>for</strong> (dynamically sized) vectors. Then we could rewrite the previous<br />

example as:<br />

double sum= 0.0;<br />

<strong>for</strong> (int i= 0; i < v.size(); i++)<br />

sum+= v[i];<br />

This is more concise and shows more clearly what we are doing.<br />

The operator overloading has the same syntax as the assignment operator and the implementation<br />

from function at:<br />

class vector<br />

{<br />

public:<br />

double& operator[](int i)<br />

{<br />

assert(i >= 0 && i < my size);<br />

return data[i];<br />

}<br />

};<br />

With this operator we can access vector elements with brackets but only if the vector is mutable<br />

vectors.<br />

3.7.3 Constant member functions<br />

This raises the more general question: How can we write operators and member functions that<br />

accept constant objects? In fact, operators are a special <strong>for</strong>m of member functions and can be<br />

called like a member function:<br />

v[i]; // is syntactic sugar <strong>for</strong>:<br />

v.operator[](i);

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

Saved successfully!

Ooh no, something went wrong!