class Abstract
{
public:
virtual void foo() const
{
std::cout << "Abstract::foo()" << std::endl;
}
void foo2() const
{
std::cout << "Abstract::foo2()" << std::endl;
}
};
class Derived: public Abstract
{
public:
void foo() const
{
std::cout << "Derived::foo()" << std::endl;
}
virtual void foo2() const
{
std::cout << "Derived::foo2()" << std::endl;
}
};
class MoreDerived: public Derived
{
public:
void foo() const
{
std::cout << "MoreDerived::foo()" << std::endl;
}
void foo2() const
{
std::cout << "MoreDerived::foo2()" << std::endl;
}
};
void PrintAbstract(const Abstract &a)
{
// a.foo();
a.foo2();
}
void PrintDerived(const Derived &d)
{
// d.foo();
d.foo2();
}
int main()
{
Abstract a;
Derived d;
MoreDerived md;
PrintAbstract(a); // Abstract::foo2(): 因为Abstract类这一层的foo()函数没有声明为virtual,所以多态机制不能运行
PrintAbstract(d); // Abstract::foo2(): 多态机制不能运行
PrintAbstract(md); // Abstract::foo2(): 多态机制不能运行
PrintDerived(d); // Derived::foo2()
PrintDerived(md); // MoreDerived::foo2(): 从Derived层开始,多态机制正确运行
}