【发布时间】:2014-04-01 10:47:09
【问题描述】:
我有大约一两年的 C++ 经验,但我的编码方式与我在 Java 中编码的方式相同(简单的 oop 内容)。现在我有这个我不明白的示例代码。 (它很大所以我试着让它更短,我希望它对你们来说足够清楚)
//in .h file
typedef void*(*AnimalCreation)();
//in .cpp
void foo(void* p)
{
AnimalCreation ac = (AnimalCreation)p;
Animal* current_animal = reinterpret_cast<Animal*>(ac());
current_animal->init();
}
//somewhere in another class foo is called
Dog* dog = new Dog(); //Dog is a subclass of Animal
foo((void*)&dog)
AnimalCreation 的目的是什么? 那和有什么区别呢
typedef void(*AnimalCreation)();`//without asterisk after void
foo 内部发生了什么?
如果 foo 接收的预期参数始终是 Animal 的子类,为什么程序员需要像上面那样实现它而不仅仅是 foo(Animal*)?
谢谢。
【问题讨论】:
-
我看不出这是如何工作的,因为
foo接收到一个指向对象的指针,并尝试将该指向对象的指针用作函数。 -
对于
AnimalCreation,它是指向不带参数并返回void *的函数的指针的类型别名。当您删除该星号时,您将获得一个指向不带参数且不返回的函数的指针(它返回void)。 -
函数指针与
void *is absolutely best avoided之间的转换。
标签: c++ casting void-pointers