忆往阁
当往事随风逝去,留下的只有回忆.


忆往阁 Yxsos.com 2017-2020
备案编号:赣ICP备15004477号

C++ 反射机制的实现

如何通过类的名称字符串来生成类的对象。比如有一个类ClassA,那么如何通过类名称字符串”ClassA”来生成类的对象呢?


CLASSFACTORY.h

#ifndef CLASSFACTORY_H
#define CLASSFACTORY_H

#include<iostream>
#include<string>
#include<map>
using namespace std;

typedef  void* (*create_fun)();

class ClassFactory
{
public:
  ~ClassFactory();

  void* getClassByName(string name)
  {
    map<string,create_fun>::iterator it=my_map.find(name);
    if(it==my_map.end())
      return NULL;
    create_fun fun=it->second;
    if(!fun)
      return NULL;

    return fun();
  }

  void registClass(string name,create_fun fun)
  {
    my_map[name]=fun;
  }

  static ClassFactory& getInstance()
  {
  static ClassFactory fac;
  return fac;
  }

private:
  ClassFactory(){}
  map<string,create_fun>my_map;

};

#endif // CLASSFACTORY_H

#include "ClassFactory.h"
ClassFactory::~ClassFactory()
{

}

Test.h

#ifndef TEST_H
#define TEST_H

#include<iostream>
using namespace std;

class Test
{
public:
  Test(){cout<<"构造函数生效"<<endl;}
  ~Test(){cout<<"析构函数生效"<<endl;}
  void print(){cout<<"调用打印函数"<<endl;}
};



#endif // TEST_H


Main

#include<iostream>
using namespace std;
#include"Test.h"
#include"ClassFactory.h"

void* create_Test()
{
  Test *t=new Test;
  return (t==NULL)?NULL:t;
}

int main()
{
  ClassFactory::getInstance().registClass("Test",create_Test);

  Test* t=(Test*)ClassFactory::getInstance().getClassByName("Test");
  if(!t)
    {
      cout<<"get instance Test err"<<endl;
      return 1;
    }

  t->print();
  delete t;

  return 0;
}

2018-02-07
59 views
暂无评论

发表评论