014
16.08.2006, 11:00 Uhr
(un)wissender
Niveauwart
|
Hallo, ich habe dir mal ein Beispiel implementiert, mit einfachem Code. Du solltest dich wirklich dringend daran orientieren, wenn ich nichts übersehen haben sollte (kommt selten vor , ist diese Klasse für deine Übungen genau die richtige.
| C++: |
//hpp #include <iosfwd> #include <cstdlib>
class FixedArray { public: explicit FixedArray(int length); FixedArray(FixedArray const& f); ~FixedArray(); FixedArray& operator= (FixedArray const& f); FixedArray& operator+=(FixedArray const & f); int & operator[]( std::size_t index); int const& operator[]( std::size_t index) const; std::size_t length() const; private: void assign(FixedArray const& f); std::size_t const _length; int * _mem; };
std::ostream& operator<<(std::ostream &out, FixedArray const& f); FixedArray const operator+(FixedArray const & f, FixedArray const & s); //cpp //#include "FixedArray.hpp" #include <algorithm> #include <stdexcept> #include <iostream> std::ostream& operator<<(std::ostream &out, FixedArray const& f) { for(std::size_t i = 0; i < f.length(); ++i) { out << f[i] << ' '; } return out; } FixedArray::FixedArray(int length) : _length(length), _mem(new int[length]) { std::fill(_mem, _mem + length, 0); }
FixedArray::FixedArray(FixedArray const& f) : _length(f._length), _mem(0) { assign(f); }
FixedArray::~FixedArray() { delete [] _mem; }
FixedArray& FixedArray::operator= (FixedArray const& f) { assign(f); return *this; }
FixedArray& FixedArray::operator+=(FixedArray const & f) { if(f.length() != length()) throw std::range_error("indexes not matching"); for(std::size_t i = 0; i < f.length(); ++i) { _mem[i] += f._mem[i]; } return *this; } FixedArray const operator+(FixedArray const & f, FixedArray const & s) { FixedArray temp(f); return temp += s; } int & FixedArray::operator[]( std::size_t index) { if(index >= _length) throw std::overflow_error("index too big"); return _mem[index]; } int const& FixedArray::operator[]( std::size_t index) const { if(index >= _length) throw std::overflow_error("index too big"); return _mem[index]; }
std::size_t FixedArray::length() const { return _length; }
void FixedArray::assign(FixedArray const& f) { int * mem = new int[f.length()]; std::copy(f._mem, f._mem + f.length(), mem); delete [] _mem; _mem = mem; } int main() { FixedArray array1(3); std::cout << "Leeres array:\n" << array1; array1[0] = 2; array1[1] = 2; array1[2] = 2; std::cout << "\nVolles erstes array:\n" << array1; try { array1[3] = 2; } catch(std::overflow_error const & ex) { std::cout << "\nZugriffsfehler:\n" << ex.what(); } FixedArray array2(3); array2[0] = 2; array2[1] = 2; array2[2] = 2; std::cout << "\nZweites array:\n" << array2; std::cout << "\nNach Addition:\n" << array1 + array2; }
|
-- Wer früher stirbt ist länger tot. Dieser Post wurde am 16.08.2006 um 11:26 Uhr von (un)wissender editiert. |