d06 ex02
This commit is contained in:
77
d06/ex02/main.cpp
Normal file
77
d06/ex02/main.cpp
Normal file
@@ -0,0 +1,77 @@
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
|
||||
#include "Classes.hpp"
|
||||
|
||||
Base * generate() {
|
||||
Base *base;
|
||||
|
||||
srand (time(NULL));
|
||||
int i = rand() % 3;
|
||||
|
||||
if (i == 0)
|
||||
{
|
||||
std::cout << "A\n";
|
||||
base = new A();
|
||||
}
|
||||
else if (i == 1)
|
||||
{
|
||||
std::cout << "B\n";
|
||||
base = new B();
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "C\n";
|
||||
base = new C();
|
||||
}
|
||||
|
||||
return base;
|
||||
}
|
||||
|
||||
void identify(Base* p) {
|
||||
A * a;
|
||||
B * b;
|
||||
C * c;
|
||||
|
||||
a = dynamic_cast<A *>(p);
|
||||
if ( a != NULL)
|
||||
std::cout << "A\n";
|
||||
b = dynamic_cast<B *>(p);
|
||||
if ( b != NULL)
|
||||
std::cout << "B\n";
|
||||
c = dynamic_cast<C *>(p);
|
||||
if ( c != NULL)
|
||||
std::cout << "C\n";
|
||||
}
|
||||
|
||||
void identify(Base& p) {
|
||||
Base base;
|
||||
try {
|
||||
base = dynamic_cast<A&>(p);
|
||||
std::cout << "<A> ";
|
||||
}
|
||||
catch ( std::exception ) {std::cout << "<not A...> ";}
|
||||
try {
|
||||
base = dynamic_cast<B&>(p);
|
||||
std::cout << "<B> ";
|
||||
}
|
||||
catch ( std::exception ) {std::cout << "<not B...> ";}
|
||||
try {
|
||||
base = dynamic_cast<C&>(p);
|
||||
std::cout << "<C> ";
|
||||
}
|
||||
catch ( std::exception ) {std::cout << "<not C...> ";}
|
||||
std::cout << "\n";
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
Base *base = generate();
|
||||
|
||||
identify(base);
|
||||
identify(*base);
|
||||
|
||||
delete base;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user