反变:把基类里指向成员函数的指针指向派生类中的成员函数。很可能导致错误,就好像把派生类指针指向基类一样。
- #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;
- }
本文通过C++代码示例介绍了反变的概念,即如何将派生类的成员函数指针转换为基类的成员函数指针。展示了不同类型的成员函数指针之间的转换,并解释了可能引发的问题。
1241

被折叠的 条评论
为什么被折叠?



