反变:把基类里指向成员函数的指针指向派生类中的成员函数。很可能导致错误,就好像把派生类指针指向基类一样。
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- void foo(){}
- };
- class Derived: public Base
- {
- public:
- void goo(){}
- };
- typedef void (Base::*MethodOfBase)();
- typedef void (Derived::*MethodOfDerived)();
- int main()
- {
- MethodOfBase methodB;
- MethodOfDerived methodD;
- methodB = static_cast<MethodOfBase>(&Derived::goo); // contravariance
- methodB = &Base::foo; // it is OK
- methodD = &Derived::goo; // it is OK
- methodD = &Base::foo; // it is OK
- return 0;
- }