Commit 016a539f by Patryk Czarnik

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

parent 49ddbb72
#include <iostream>
#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() {
std::cout << "Początek programu\n";
Wektor w;
......@@ -26,6 +35,8 @@ int main() {
std::cout <<"size: " << w.size() << '\n';
std::cout << w << '\n';
std::cout << "\nsuma wynosi: " << suma(w) << '\n';
// EXN w.set(50, 5050);
try {
......@@ -35,6 +46,8 @@ int main() {
std::cout << "wyjątek " << exn << '\n';
}
std::cout << "\nsuma wynosi: " << suma(w) << '\n';
std::cout << "Koniec programu\n";
return 0;
}
......@@ -11,6 +11,7 @@ Wektor::Wektor()
}
Wektor::~Wektor() {
std::cout << "destruct\n";
delete[] t;
}
......@@ -32,6 +33,13 @@ void Wektor::push_back(TypWartosci 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) {
if(idx < 0 || idx >= liczba_elementow) {
throw "indeks poza zakresem";
......
......@@ -28,8 +28,9 @@ public:
void push_back(TypWartosci e);
/** 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);
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