====== 3 - Dědičnost, přetížení operátorů ======
===== Jednoduchá dědičnost =====
#include
class TridaA
{
protected:
virtual void metoda ()
{
std::cout << "metoda A" << std::endl;
}
public:
void run ()
{
metoda ();
}
};
class TridaB : public TridaA
{
protected:
void metoda ()
{
std::cout << "metoda B" << std::endl;
}
};
int main ()
{
TridaA a;
a.run ();
TridaB b;
b.run ();
return 0;
}
===== Přetížení operátoru - komplexní čísla =====
#include
using namespace std;
struct complex
{
double re, im;
};
complex operator+ (complex a, complex b)
{
complex tmp;
tmp.re = a.re + b.re;
tmp.im = a.im + b.im;
return tmp;
}
ostream & operator<< (ostream &vstup, complex x)
{
vstup << x.re << " + j" << x.im << endl;
return vstup;
}
int main ()
{
complex X = {2.3, 4.8};
complex Y = {3.2, 8.4};
complex Z;
Z = X + Y;
std::cout << Z.re << " + j" << Z.im << std::endl;
cout << Z;
return 0;
}
===== Práce se soubory - exceptions =====
#include
#include
int main ()
{
std::ifstream file;
file.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try
{
// potencialne rizikovy kod - muze ukoncit beh programu
file.open ("text.txt");
while (!file.eof()) file.get();
file.close();
}
catch (std::ifstream::failure e)
{
// kod, ktery osetruje vyjimku
std::cout << "I/O chyba pri praci se souborem" << std::endl;
std::cout << e.what() << std::endl;
}
std::cout << "beh programu dale pokracuje" << std::endl;
return 0;
}