class A
{
public:
void func_A() { func_B(); }
void func_B() { cout << "A:func_B" << endl; }
};
class B : public A
{
public:
void func_B() { cout << "B:func_B" << endl; }
};
int main()
{
B b;
b.func_A();
system("pause");
return 0;
}
输出结果是:A:func_B
class A
{
public:
void func_A() { func_B(); }
virtual void func_B() { cout << "A:func_B" << endl; }
};
class B : public A
{
public:
void func_B() { cout << "B:func_B" << endl; }
};
int main()
{
B b;
b.func_A();
system("pause");
return 0;
}
输出结果是:B:func_B
我的理解是,在类成员函数中的this指针,类型均是与该类相同,调用时this的值为调用对象的地址,但是这个对象不一定是该类类型,有可能是派生类类型。
上面的两个例子中,在classA的func_A里,this指针为A类型,通过b.func_A()派生类对象调用基类函数时,func_A中的this指针指向b,所以在func_A中,通过隐藏的this调用func_B的方式,满足最常见的虚函数动态多态性特征(基类指针指向派生类,调用同名函数)。