在 C++ 中,函数指针是类型安全的。你必须做一些非常愚蠢的事情来打破它们(通常涉及铸造、联合、memcpy
或类似的东西;它不会偶然发生)。
但是,在 C 中,函数类型没有那么严格。你可以这样做:
int add(int a, int b){ return a + b; }
int add_f(float a, float b){ return a + b; }
int (*f)(); // empty argument list does NOT mean zero arguments.
// for zero arguments, say int (*)(void)
f = &add;
f = &add_f;
http://ideone.com/Y6mCc
我被问到一个非常愚蠢的例子。 这里是:
#include <iostream>
int add(int a, int b){ return a + b; }
int add_f(float a, float b){ return a + b; }
union {
int (*f1)(int, int);
int (*f2)(float, float);
} fp;
int main(void)
{
fp.f1 = &add;
std::cout << "Expected (1): " << add(1, 3) << std::endl;
std::cout << "Actual (1): " << (fp.f1)(1, 3) << std::endl;
std::cout << "Expected (2): " << add(1.0f, 3.0f) << std::endl;
std::cout << "Actual (2): " << (fp.f2)(1.0f, 3.0f) << std::endl;
fp.f2 = &add_f;
std::cout << "Expected (3): " << add_f(1.0f, 3.0f) << std::endl;
std::cout << "Actual (3): " << (fp.f2)(1.0f, 3.0f) << std::endl;
std::cout << "Expected (4): " << add_f(1, 3) << std::endl;
std::cout << "Actual (4): " << (fp.f1)(1, 3) << std::endl;
return 0;
}
请注意,这种愚蠢在带有Marshal.Copy
.