[英]C++ Understanding Functors Polymorphism
我尝试实现多态仿函数对象(纯抽象基类和子代)仅出于理解目的。 我的目标是创建许多使用纯虚函数的不同实现的基类对象。
当我创建基类的指针并将其设置为新的子类时,我无法将对象作为函数调用。 错误是:
main.cpp:29:7: error: ‘a’ cannot be used as a function
这是代码:
#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;
}
我目前的理解是“ foo * a”将功能对象“ bar”的地址存储在a中(如cout语句所示)。 因此,取消引用“ * a”应该提供对“ a”指向的函数的访问,而“ * a()”应该调用它。
但事实并非如此。 谁能告诉我为什么?
既然你有一个指针a
,你必须取消对它的引用调用()操作:
(*a)(); // Best use parentheseis around the dereferenced instance
当取消引用a时,您丢弃了多态性,应该调用foo::operator()
而不是bar::operator()
,从而引发纯虚拟函数调用异常 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.