导航:首页 - C++反射的一种实现方式

C++反射的一种实现方式
作者:深圳教育在线 来源:www.szedu.net 更新日期:2009-8-12
  #pragma once
  #include <list>
  class Reflector
  {
  public:
  virtual ~Reflector();
  virtual const char* getClassName() = 0;
  static std::list<Reflector*> m_lstRef;
  };
  #pragma once
  #include <list>
  class Reflector
  {
  public:
  virtual ~Reflector();
  virtual const char* getClassName() = 0;
  static std::list<Reflector*> m_lstRef;
  };
  Reflector.cpp:
  view plaincopy to clipboardprint?
  #include "Reflector.h"
  Reflector::~Reflector()
  {
  }
  std::list<Reflector*>Reflector:: m_lstRef;
  #include "Reflector.h"
  Reflector::~Reflector()
  {
  }
  std::list<Reflector*>Reflector:: m_lstRef;
  A.h:
  view plaincopy to clipboardprint?
  #pragma once
  #include "Reflector.h"
  class A : public Reflector
  {
  public:
  virtual ~A();
  //如果你觉得重复,可以把函数getClassName弄成宏
  virtual const char* getClassName();
  };
  #pragma once
  #include "Reflector.h"
  class A : public Reflector
  {
  public:
  virtual ~A();
  //如果你觉得重复,可以把函数getClassName弄成宏
  virtual const char* getClassName();
  };
  A.cpp:
  view plaincopy to clipboardprint?
  #include "A.h"
  A::~A()
  {
  }
  const char* A::getClassName()
  {
  return "A";
  }
  #include "A.h"
  A::~A()
  {
  }
  const char* A::getClassName()
  {
  return "A";
  }
  main.cpp:
  view plaincopy to clipboardprint?
  #include "Reflector.h"
  #include "A.h"
  #include <iostream>
  #include <string>
  using namespace std;
  void init()
  {
  Reflector::m_lstRef.push_back(new A);
  }
  int main()
  {
  init();
  //从别处(比如配置文件)得知要创建的是对象A
  const std::string className = "A";
  for (std::list<Reflector*>::iterator it = Reflector::m_lstRef.begin();
  it != Reflector::m_lstRef.end(); ++it)
  {
  if (className == (*it)->getClassName())
  {
  cout << "A" << endl;
  }
  }
  return 0;
  }
  #include "Reflector.h"
  #include "A.h"
  #include <iostream>
  #include <string>
  using namespace std;
  void init()
  {
  Reflector::m_lstRef.push_back(new A);
  }
  int main()
  {
  init();
  //从别处(比如配置文件)得知要创建的是对象A
  const std::string className = "A";
  for (std::list<Reflector*>::iterator it = Reflector::m_lstRef.begin();
  it != Reflector::m_lstRef.end(); ++it)
  {
  if (className == (*it)->getClassName())
  {
  cout << "A" << endl;
  }
  }
  return 0;
  }

报 名 此 课 程 / 咨 询 相 关 信 息
【预约登门】 【网上咨询】 【订座试听】 【现在报名】
课程名称
C++反射的一种实现方式
真实姓名
* 性 别
联系电话
* E-mail:
所在地区
咨询内容

      

相关文章:

Copyright© 2004-2010 www.szedu.net 深圳教育在线 版权所有
中国·深圳
粤ICP备06023013号