#include <iostream>
#include <memory>
using namespace std;
class Base { public: virtual ~Base() = default; /* 使其多态 */ };
class A : public Base { public:void show1() { printf("1\n"); } };
class B : public Base { public:void show2() { printf("2\n"); } };
void f(shared_ptr<Base> c)
{
if (dynamic_pointer_cast<A>(c).get())
{
static_pointer_cast<A>(c)->show1();
}
else if (dynamic_pointer_cast<B>(c).get())
{
static_pointer_cast<B>(c)->show2();
}
}
int main()
{
auto c1 = make_shared<A>();
auto c2 = make_shared<B>();
f(move(c1));
f(move(c2));
}
#include <iostream>
#include <memory>
using namespace std;
enum class CT { A, B };
class Base { public: virtual CT id() const = 0; virtual ~Base() = default; /* 使其多态 */ };
class A : public Base { public:void show1() { printf("1\n"); }; CT id() const override { return CT::A; } };
class B : public Base { public:void show2() { printf("2\n"); }; CT id() const override { return CT::B; } };
void f(Base* c)
{
switch (c->id())
{
case CT::A:
reinterpret_cast<A*>(c)->show1();
break;
case CT::B:
reinterpret_cast<B*>(c)->show2();
break;
}
}
int main()
{
auto c1 = new A();
auto c2 = new B();
f(c1);
f(c2);
delete c1;
delete c2;
}
See alse:
原文:https://www.cnblogs.com/ajanuw/p/14853841.html