JavaScript のように実行時にオブジェクトを作成したい:
person=new Object();
person.firstname="John";
json を解析してオブジェクトに保存します。メソッドは事前に知られており、コンパイルされます。この簡単な例を作成しましたが、正しい方向に進んでいるかどうかを知りたいです。
文字列によるメソッドの追加と呼び出し。関数 male と female がオブジェクトへのメソッドとしてオブジェクトに追加されます。
現在、オブジェクトには性別のプロパティがありますが、後で関数と同じことをしたいと思います。メソッドによって、ObjectsetProperty
で宣言されます。getProperty
それは良い考えですか?
typedef struct method
{
(void)(*method_fn)(Object * _this, string params);
string method_name;
} method;
class Object{
private:
vector<method> methods;
public:
string gender;
Object(){};
~Object(){};
void addMethod(method metoda);
bool callMethod(string methodName,string params);
};
void male(Object *_this,string params) {
_this->gender="Male";
}
void female(Object* _this,string params) {
_this->gender="Female";
}
void Object::addMethod(method metoda)
{
methods.push_back(metoda);
}
bool Object::callMethod(string methodName,string params){
for(unsigned int i=0;i<methods.size();i++)
{
if(methods[i].method_name.compare(methodName)==0)
{
(*(methods[i].method_fn))(this,params);
return true;
}
}
return false;
}
使って仕事です。
int _tmain(int argc, _TCHAR* argv[])
{
Object *object1 = new Object();
Object *object2 = new Object();
method new_method;
new_method.method_fn=♂
new_method.method_name="method1";
object2->addMethod(new_method);
new_method.method_fn=♀
new_method.method_name="method2";
object2->addMethod(new_method);
object1->callMethod("method1","");
object2->callMethod("method2","");
return 0;
}