C++/Przeciążanie operatorów: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
→‎Przykład zastosowania: zmiana klasy aby można było przechować tablicę DOWOLNEGO typu danych
Linia 46:
ostream & operator<< (ostream &wyjscie, const Student &s)
{
return wyjscie << "Nr indeksu : " <<s.nr_indeksu << endl << "Srednia ocen : " <<s.srednia_ocen<<endl;
return wyjscie;
}
</source>
Linia 76 ⟶ 75:
//...
public:
int operator==(const Student &q) {return nr_indeksu==q.nr_indeksu};
int operator==(const int &q) {return nr_indeksu==q};
};
</source>
Linia 125 ⟶ 124:
#include <iostream>
using namespace std;
template <typename T, int el>
class TablicaIntTablica
{
public:
TablicaIntTablica() : L_elementow(el) {}
operator bool() const {return (L_elementow != 0);}
bool operator!() const {return (L_elementow == 0);}
 
private:
intT Tab[el];
intsize_t L_elementow;
};
 
Linia 141 ⟶ 140:
{
const n = 5;
TablicaIntTablica <short, n> tab;
 
if(tab)
Linia 148 ⟶ 147:
cout << "Tablica jest pusta." << endl;
 
TablicaIntTablica <short, 0> tab2;
 
if(tab2)
Linia 171 ⟶ 170:
W niektórych przypadkach bardzo przydatny jest operator indeksu '''[]'''. Można go przeciążyć oczywiście w dowolny sposób, ale chyba najbardziej intuicyjne jest przypisanie mu funkcji dostępu do konkretnego elementu np. w tablicy.
 
Posługując się przykładem klasy '''TablicaIntTablica''' możemy dopisać do niej następujące dwa operatory:
 
<source lang="cpp">
intT & operator[](intsize_t el) {return Tab[el];}
const intT & operator[](intsize_t el) const {return Tab[el];}
</source>
 
Linia 184 ⟶ 183:
{
const n = 5;
TablicaInt <short, n> tab;
 
for(int i = 0; i < n; ++i)