C++实现多态的注意事项
-->C++这种悲催的语言,虽然标榜"面向对象",但是只有函数参数是指针或引用类型时才支持面向对象;反倒是C++中最基础的类,如果函数参数是类类型,是不支持面向对象的
-->只有指针和引用才可能有动态类型
-->多态必须是指针或者引用
-->多态的前提是赋值兼容
#include <iostream> #include <string> #include <typeinfo> //使用typeid需要包含typeinfo头文件 using namespace std; class Base { public: virtual ~Base() { } virtual void printf() { cout<<"I am a Base."<<endl; } }; class Derived : public Base { public: void printf() { cout<<"I am a Derived."<<endl; } }; void test(Base b)//C++多态的前提是 指针或者引用,单纯的类类型不能实现多态 { b.printf(); } void test(Base* b)//指针类型可以实现多态 { b->printf(); } void test(Base& b)//引用类型可以实现多态 { b.printf(); } int main() { Base b; Derived d; test(b); test(d); test(&b); test(&d); return 0; }
运行结果: