C/C++教程

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

本文主要是介绍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:

  • shared_ptr
这篇关于c++ 智能指针 shared_ptr 在多态上的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!