c++ 智能指针 shared_ptr 在多态上的使用

#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:

posted @ 2021-06-05 20:55  Ajanuw  阅读(817)  评论(0编辑  收藏  举报