Próbuję implementować polimorficzne obiekty funktora (czysta abstrakcyjna klasa bazowa i dzieci) wyłącznie w celu zrozumienia. Moim celem jest stworzenie wielu obiektów klasy bazowej, które używają różnych implementacji czystych funkcji wirtualnych.C++ Understanding Functors Polymorphism
Gdy utworzę wskaźnik klasy bazowej i ustawię go na równi nowej klasie potomnej, nie będę mógł wywołać obiektu jako funkcji. Błąd jest:
main.cpp:29:7: error: ‘a’ cannot be used as a function
Oto kod:
#include <iostream>
class foo{
public:
virtual void operator()() = 0;
virtual ~foo(){}
};
class bar: public foo{
public:
void operator()(){ std::cout << "bar" << std::endl;}
};
class car: public foo{
public:
void operator()(){ std::cout << "car" << std::endl;}
};
int main(int argc, char *argv[])
{
foo *a = new bar;
foo *b = new car;
//prints out the address of the two object:
//hence I know that they are being created
std::cout << a << std::endl;
std::cout << b << std::endl;
//does not call bar() instead returns the error mentioned above
//I also tried some obscure variation of the theme:
//*a(); *a()(); a()->(); a->(); a()();
//just calling "a;" does not do anything except throwing a warning
a();
//the following code works fine: when called it print bar, car respectivly as expected
// bar b;
// car c;
// b();
// c();
delete b;
delete a;
return 0;
}
Mój obecny zrozumienia jest to, że „foo * A” przechowuje adres obiektu funkcja „bar” w (jak pokazano instrukcja cout). Dlatego wyodrębnienie go "* a" powinno zapewnić dostęp do funkcji, do której "a" się odnosi i "* a()" powinien ją nazwać.
Ale tak nie jest. Czy ktoś może mi powiedzieć dlaczego.