首页 > 编程语言 > 详细

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

时间:2021-06-06 00:34:08      阅读:44      评论:0      收藏:0      [点我收藏+]
#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:

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

原文:https://www.cnblogs.com/ajanuw/p/14853841.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!