Commit 49ddbb72 by Patryk Czarnik

operator[] w wersji z referencją

parent 88c368b2
...@@ -8,10 +8,12 @@ int main() { ...@@ -8,10 +8,12 @@ int main() {
w.push_back(10); w.push_back(10);
w.push_back(11); w.push_back(11);
w.push_back(12); w.push_back(12);
std::cout << "Element nr 0: " << w.get(0) << '\n'; std::cout << "Element nr 0: " << w[0] << '\n';
std::cout << "Element nr 2: " << w.get(2) << '\n'; std::cout << "Element nr 2: " << w[2] << '\n';
w.set(2, 22); // w.set(2, 2222);
std::cout << "Element nr 2: " << w.get(2) << '\n'; w[2] = 2220;
w[2] += 2;
std::cout << "Element nr 2: " << w[2] << '\n';
std::cout <<"size: " << w.size() << '\n'; std::cout <<"size: " << w.size() << '\n';
std::cout << '\n'; std::cout << '\n';
...@@ -27,7 +29,7 @@ int main() { ...@@ -27,7 +29,7 @@ int main() {
// EXN w.set(50, 5050); // EXN w.set(50, 5050);
try { try {
w.set(50, 5050); w[50] = 5050;
std::cout << "udało się ustawić element 50\n"; std::cout << "udało się ustawić element 50\n";
} catch(const char *exn) { } catch(const char *exn) {
std::cout << "wyjątek " << exn << '\n'; std::cout << "wyjątek " << exn << '\n';
......
...@@ -32,21 +32,14 @@ void Wektor::push_back(TypWartosci e) { ...@@ -32,21 +32,14 @@ void Wektor::push_back(TypWartosci e) {
t[liczba_elementow++] = e; t[liczba_elementow++] = e;
} }
void Wektor::set(TypIndeksu idx, TypWartosci e) { TypWartosci& Wektor::operator[](TypIndeksu idx) {
if(idx < 0 || idx >= liczba_elementow) {
throw "indeks poza zakresem";
}
t[idx] = e;
}
TypWartosci Wektor::get(TypIndeksu idx) {
if(idx < 0 || idx >= liczba_elementow) { if(idx < 0 || idx >= liczba_elementow) {
throw "indeks poza zakresem"; throw "indeks poza zakresem";
} }
return t[idx]; return t[idx];
} }
std::ostream& operator<<(std::ostream& out, const Wektor& w) { std::ostream& operator<<(std::ostream& out, const Wektor& w) {
out << '['; out << '[';
for(TypIndeksu i=0; i<w.liczba_elementow; i++) { for(TypIndeksu i=0; i<w.liczba_elementow; i++) {
out << w.t[i] << ", "; out << w.t[i] << ", ";
......
...@@ -27,11 +27,10 @@ public: ...@@ -27,11 +27,10 @@ public:
/** Dodanie nowego elementu na końcu. */ /** Dodanie nowego elementu na końcu. */
void push_back(TypWartosci e); void push_back(TypWartosci e);
/** Przypisanie nowej wartości na podanej pozycji. */
void set(TypIndeksu idx, TypWartosci e);
/** Odczyt wartości spod podanej pozycji. */ /** Odczyt wartości spod podanej pozycji. */
TypWartosci get(TypIndeksu idx);
/** Dostęp do wartości na podanej pozycji. */
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