Как передать указатель функции, который указывает конструктору?

Посмотрите на http://docs.jquery.com/Ajax/serialize .

Это сделало бы следующий пример:

$("#submit").click(function() {
    $.ajax({
        data: $("form").serialize(),
        ...rest
    });
});

33
задан Kareem 5 June 2009 в 06:48
поделиться

3 ответа

Вы не можете взять адрес конструктора (Конструкторы C ++ 98 Standard 12.1 / 12 - «Конструкторы 12.1-12 -« Адрес конструктора не должен приниматься »)

Лучше всего иметь фабричную функцию / метод, который создает объект и передает адрес фабрики:

class Object;

class Class{
public:
   Class(const std::string &n, Object *(*c)()) : name(n), create(c) {};
protected:
   std::string name;     // Name for subclass
   Object *(*create)();  // Pointer to creation function for subclass
};

class Object {};

Object* ObjectFactory()
{
    return new Object;
}



int main(int argc, char**argv)
{
    Class foo( "myFoo", ObjectFactory);

    return 0;
}
58
ответ дан 27 November 2019 в 18:07
поделиться

Хм, странно. create - это переменная-член, то есть она доступна только в экземплярах класса, но ее цель, похоже, заключается в создании экземпляра в первую очередь.

Вы не можете взять адрес конструктора, но можете создать статический фабричные методы и возьмите адрес.

2
ответ дан 27 November 2019 в 18:07
поделиться

You can't use regular function pointers on methods, you have to use method pointers, which have bizarre syntax:

void (MyClass::*method_ptr)(int x, int y);
method_ptr = &MyClass::MyMethod;

This gives you a method pointer to MyClass's method - MyMethod. However this isn't a true pointer in that it's not an absolute memory address, it's basically an offset (more complicated than that due to virtual inheritance, but that stuff is implementation specific) into a class. So to use the method pointer, you have to supply it with a class, like this:

MyClass myclass;
myclass.*method_ptr(x, y);

or

MyClass *myclass = new MyClass;
myclass->*method_ptr(x, y);

Of course it should be obvious at this point that you can't use a method pointer to point to an objects constructor. In order to use a method pointer you need to have an instance of the class so it's constructor has already been called! So in your case Michael's Object Factory suggestion is probably the best way of doing it.

1
ответ дан 27 November 2019 в 18:07
поделиться
Другие вопросы по тегам:

Похожие вопросы: