重载:
成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual 关键字可有可无。
1 #include <iostream> 2 3 using std::cin; 4 using std::cout; 5 using std::endl; 6 7 class A 8 { 9 public: 10 void show(int val) { cout << val; } 11 void show(double val) { cout << val; } 12 }; 13 14 int main(void) 15 { 16 A a; 17 a.show(4); 18 cout << endl; 19 a.show(4.2); 20 cin.get(); 21 }
覆盖(重写):
覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual 关键字。
1 #include <iostream> 2 3 using std::cin; 4 using std::cout; 5 using std::endl; 6 7 class A 8 { 9 public: 10 virtual void show(int val) { cout << val; } 11 }; 12 13 class B : public A 14 { 15 public: 16 void show(int val) { cout << "--" << val << "--"; } 17 }; 18 19 int main(void) 20 { 21 A a; 22 a.show(4); 23 cout << endl; 24 25 A* p = new B; 26 p->show(5); 27 28 cin.get(); 29 }