class A {
virtual void t2()
{ cout<<"A::t2()"<<endl; }
public:
void func()
{ t2(); cout<<"A::f()"<<endl; }
};
class B : public A {
virtual void t2()
{ cout<<"B::t2()"<<endl; }
public:
void func()
{ t2(); cout<<"B::f()"<<endl; }
};
int main()
{ B b;
A * p = &b;
p->func();
b.func();
return 0;
}
#include<iostream>
using namespace std;
class CBase
{
public:
virtual void print()
{
cout << "CBase::print()" << endl;
}
};
class CDerived : public CBase
{
public:
/7oid print(){ cout << "CDerived::print()" << endl; }
void print(int i)
{
cout << i << endl;
}
};
int main()
{
CDerived derived;
derived.print(0); // 此时调用的不是虚函数
//derived.print(); // 此调用非法,因为基类的该函数被隐藏了
// (dynamic_cast<CBase&>(derived)).print(); // 向上转型(Upcasting),此时等同于static_cast,反之不行
CBase * pBase = &derived;
pBase->print(); // 调用的是虚函数,因为通过基类指针看到的是基类的函数
return 0;
}