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.

82 CHAPTER 3. CLASSES<br />

class matrix<br />

{<br />

public:<br />

matrix() : nrows(0), ncols(0), data(0) {}<br />

matrix(int nrows, int ncols)<br />

: nrows(nrows), ncols(ncols), data( new double[nrows ∗ ncols] ) {}<br />

matrix(const matrix& that)<br />

: nrows(that.nrows), ncols(that.ncols), data(new double[nrows ∗ ncols])<br />

{<br />

<strong>for</strong> (int i= 0, size= nrows∗ncols; i < size; ++i)<br />

data[i]= that.data[i];<br />

}<br />

∼matrix() { if (data) delete [] data; }<br />

void operator=(const matrix& that)<br />

{<br />

assert(nrows == that.nrows && ncols == that.ncols);<br />

<strong>for</strong> (int i= 0, size= nrows∗ncols; i < size; ++i)<br />

data[i]= that.data[i];<br />

}<br />

int num rows() const { return nrows; }<br />

int num cols() const { return ncols; }<br />

private:<br />

int nrows, ncols;<br />

double∗ data;<br />

};<br />

So far, the implementation is done in the same manner as be<strong>for</strong>e: variables are private, the<br />

constructors establish defined values <strong>for</strong> all members, the copy constructor and the assignment<br />

are consistent, size in<strong>for</strong>mation are provided by a constant function.<br />

What is still missing is the access to the matrix entries.<br />

Be aware!<br />

The bracket operator accepts only one argument.<br />

That means we cannot define<br />

double& operator[](int r, int c) { ... }<br />

Approach 1: Parenthesis<br />

The simplest way handling multiple indices is replacing the square brackets with parentheses:<br />

double& operator()(int r, int c)

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

Saved successfully!

Ooh no, something went wrong!