目前有个需求想采用字符串的方式创建对象,用CRuntimeClass::CreateObject("classname");总是返回NULL
class A:public CObject
{
DECLARE_DYNCREATE(A)
};
IMPLEMENT_DYNCREATE(A,CObject)
///
A* a=CRuntimeClass::CreateObject("A");
返回一个NULL,就是说在Runtime那个列表里没有找到A这个类。
但是MSDN中有下文,模拟试验了一下,也同样返回空指针,请问为什么呢// This example creates an object if CMyClass is defined.CRuntimeClass* pMyRTClass= pMyObject->GetRuntimeClass();CRuntimeClass* pClass = pMyRTClass->FromName("CMyClass");
if (pClass == NULL)
{
// not found, display a warning for diagnostic purposes
AfxMessageBox("Warning: CMyClass not defined");
return NULL;
}// attempt to create the object with the found CRuntimeClass
CObject* pObject = pClass->CreateObject();
class A:public CObject
{
DECLARE_DYNCREATE(A)
};
IMPLEMENT_DYNCREATE(A,CObject)
///
A* a=CRuntimeClass::CreateObject("A");
返回一个NULL,就是说在Runtime那个列表里没有找到A这个类。
但是MSDN中有下文,模拟试验了一下,也同样返回空指针,请问为什么呢// This example creates an object if CMyClass is defined.CRuntimeClass* pMyRTClass= pMyObject->GetRuntimeClass();CRuntimeClass* pClass = pMyRTClass->FromName("CMyClass");
if (pClass == NULL)
{
// not found, display a warning for diagnostic purposes
AfxMessageBox("Warning: CMyClass not defined");
return NULL;
}// attempt to create the object with the found CRuntimeClass
CObject* pObject = pClass->CreateObject();
A *a = new A;
看看。
class Subject;
class IObserver
{
public:
virtual void OnUpdate(Subject* su,CObject* arg)=0;
};class Subject:public CObject
{
DECLARE_DYNAMIC(Subject)
protected:
CArray<IObserver*> observers;
public:
void addObserver(IObserver* ob)
{
observers.Add(ob);
}
void notifyObservers()
{
for(int i=0;i<observers.GetSize();i++)
{
observers[i]->OnUpdate(this,NULL);
}
}
};class MyTest:public Subject
{
DECLARE_DYNAMIC(MyTest)
public:
void setSomeThing()
{
this->notifyObservers();
}
};class MyTest2:public Subject
{
DECLARE_DYNAMIC(MyTest2)
public:
void setSomeThing()
{
this->notifyObservers();
}
};
IMPLEMENT_DYNAMIC(Subject, CObject)
IMPLEMENT_DYNAMIC(MyTest,Subject)
IMPLEMENT_DYNAMIC(MyTest2,Subject)
////实现一个观察者模式
MyTest* t=(MyTest*)(CRuntimeClass::CreateObject("MyTest"));
t->setSomeThing();
我尝试想动态创建的时候返回了NULL,没看出什么问题啊
其实是声明一个static对象其中将类字符串加入到runtime列表中了。
但编译器发出A类没有在程序运行过程中使用过,所以不对a进行编译。所以也不会生成
那个static对象。所以A类不会在runtime列表中了。解决方法:
动态创建前,声明一个A的实例。并调用A实例的一个有意思的方法。以强迫编译入A的
相关内容