C++——虚方法 引言:当我们希望同一个方法在基类和派生类中的行为是不同的,也就是说,方法的行为应取决于调用方法的对象,即要改写方法。
虚方法的作用:当方法是通过引用或指针调用时,可确定使用哪一个方法
#ifndef Customer.h class Customer { private: long account; public: Customer(long acc&); virtual withdraw(long account &) const; }; class CustomerPlus : public Customer { private: ... public: CustomerPlus(long &acc); virtual withdraw(long account &) const; }; #endif说明: 1、声明一个基类Customer,CustomerPlus为派生类 2、在方法名前加上virtual即将该方法声明为虚方法 3、方法在基类被声明为虚的后,它在派生类自动成为虚方法,在派生类中使用virtual来指出可作提示
使用: 若withdraw()不是虚的
Customer Jack(123); CustomerPlus Ben(456); Customer &pt1=Jack; Customer &pt2=Ben;//注意类型和引用不匹配 pt1.withdraw(123);//使用Customer::withdraw() pt2.withdraw(456);//使用Customer::withdraw()若withdraw()是虚的
Customer Jack(123); CustomerPlus Ben(456); Customer &pt1=Jack; Customer &pt2=Ben; pt1.withdraw(123);//使用Customer::withdraw() pt2.withdraw(456);//使用CustomerPlus::withdraw()总结: 将方法声明为虚的,如果指针或引用与类型不匹配,可确定使用哪一个方法
