C++如何动态的生成对象详解

2020-01-06 16:44:12王振洲

5、基类,所有对象的基类,m_propertyMap成员是存储属性和属性对于的set接口对


class CBaseClass
{
public:
 CBaseClass() {}
 virtual ~CBaseClass() {}

public:
 std::map<std::string, SetValueProperty> m_propertyMap;

private:
};

测试类


class CHelloClass : public CBaseClass
{
public:
 DECLARE_CLASS(CHelloClass);
 ACCESS_INTERFACE(CHelloClass, int, Age, "年龄")
 ACCESS_INTERFACE(CHelloClass, int, Sex, "性别")

public:
 CHelloClass();
 virtual ~CHelloClass();

public:
 static void * Instance();
 
public:
 virtual void RegistProperty( );

protected:
 int m_Age = 0;
 int m_Sex = 0;
};

CHelloClass类是一个测试类,用于测试第三节所写的动态生成对象是否正确,RegistProperty接口里边是对属性的注册

1、测试main函数


int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);


 CHelloClass * pVar = (CHelloClass*)CClassFactory::IntanceFactory().CreateObject("CHelloClass");
 if (pVar)
 {
 int pAge = 2;
 int pSex = 1;

 pVar->m_propertyMap["Age"](pVar, &pAge);
 pVar->m_propertyMap["Sex"](pVar, &pSex);

 std::cout << pVar->GetAgeDescribe() << pVar->GetAge() << std::endl;
 std::cout << pVar->GetSexDescribe() << pVar->GetSex() << std::endl;
 }

 return a.exec();
}

2、效果结果截图

c,动态对象,动态生成对象,动态创建对象

图1 CHelloClass测试结果

序列化和反序列化

本片文章主要讲解的是动态生成对象,并没有打算深入的去剖析系列化和反序列化的模块,demo中也有一小部分的序列化代码,主要是使用tinyxml2来读文件,代码如下:


void DynamicObject::Deserialize()
{
 tinyxml2::XMLDocument doc;
 if (tinyxml2::XML_NO_ERROR == doc.LoadFile("D:examplepaintDynamicCreateObjecttest.xml"))
 {
  if (tinyxml2::XMLNode * rootNode = doc.FirstChildElement("Ojbectlist"))
  {
   const char * rootText = rootNode->ToElement()->Attribute("name");

   tinyxml2::XMLElement * element = rootNode->FirstChildElement("Object");
   while (element)
   {
    const char * objectName = element->Attribute("name");
    tinyxml2::XMLElement * propertyElement = element->FirstChildElement("Property");
    while (propertyElement)
    {
     const char * propertyName = propertyElement->Attribute("name");
     const char * propertyValue = propertyElement->Attribute("value");
    }
    tinyxml2::XMLNode * nextNode = element->NextSibling();
    if (nextNode == nullptr)
    {
     break;
    }
    element = nextNode->ToElement();
   }
  }
 }
}