Commit 016a539f by Patryk Czarnik

operator[] w dwóch wersjach + funkcja suma w programie

parent 49ddbb72
#include <iostream> #include <iostream>
#include "wektor.h" #include "wektor.h"
// napiszmy funkcję, która oblicza sumę elementów przekazanego Wektora...
TypWartosci suma(const Wektor &wektor) {
TypWartosci suma = 0;
for(TypIndeksu i = 0; i < wektor.size(); i++) {
suma += wektor[i];
}
return suma;
}
int main() { int main() {
std::cout << "Początek programu\n"; std::cout << "Początek programu\n";
Wektor w; Wektor w;
...@@ -26,6 +35,8 @@ int main() { ...@@ -26,6 +35,8 @@ int main() {
std::cout <<"size: " << w.size() << '\n'; std::cout <<"size: " << w.size() << '\n';
std::cout << w << '\n'; std::cout << w << '\n';
std::cout << "\nsuma wynosi: " << suma(w) << '\n';
// EXN w.set(50, 5050); // EXN w.set(50, 5050);
try { try {
...@@ -35,6 +46,8 @@ int main() { ...@@ -35,6 +46,8 @@ int main() {
std::cout << "wyjątek " << exn << '\n'; std::cout << "wyjątek " << exn << '\n';
} }
std::cout << "\nsuma wynosi: " << suma(w) << '\n';
std::cout << "Koniec programu\n"; std::cout << "Koniec programu\n";
return 0; return 0;
} }
...@@ -11,6 +11,7 @@ Wektor::Wektor() ...@@ -11,6 +11,7 @@ Wektor::Wektor()
} }
Wektor::~Wektor() { Wektor::~Wektor() {
std::cout << "destruct\n";
delete[] t; delete[] t;
} }
...@@ -32,6 +33,13 @@ void Wektor::push_back(TypWartosci e) { ...@@ -32,6 +33,13 @@ void Wektor::push_back(TypWartosci e) {
t[liczba_elementow++] = e; t[liczba_elementow++] = e;
} }
TypWartosci Wektor::operator[](TypIndeksu idx) const {
if(idx < 0 || idx >= liczba_elementow) {
throw "indeks poza zakresem";
}
return t[idx];
}
TypWartosci& Wektor::operator[](TypIndeksu idx) { TypWartosci& Wektor::operator[](TypIndeksu idx) {
if(idx < 0 || idx >= liczba_elementow) { if(idx < 0 || idx >= liczba_elementow) {
throw "indeks poza zakresem"; throw "indeks poza zakresem";
......
...@@ -28,8 +28,9 @@ public: ...@@ -28,8 +28,9 @@ public:
void push_back(TypWartosci e); void push_back(TypWartosci e);
/** Odczyt wartości spod podanej pozycji. */ /** Odczyt wartości spod podanej pozycji. */
TypWartosci operator[](TypIndeksu idx) const;
/** Dostęp do wartości na podanej pozycji. */ /** Dostęp do wartości na podanej pozycji. Tutaj wynikiem jest referencja jako tzw. "lvalue". */
TypWartosci& operator[](TypIndeksu idx); TypWartosci& operator[](TypIndeksu idx);
friend std::ostream& operator<<(std::ostream&, const Wektor&); friend std::ostream& operator<<(std::ostream&, const Wektor&);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment