目錄
子類繼承父類重載
類成員函數重載
繼承和組合的三種方式請看我上一篇文章
C++筆記(二)--- 繼承和組合-CSDN博客
子類繼承父類重載
當子類繼承父類之后,子類重新定義了一個和父類完全相同函數名稱的函數時,會將父類所有相同函數名的函數覆蓋掉
class person
{
public:person(){}void printf(){ cout << "This is person no parameter printf!" << endl;}void printf(string s} { cout << "This is person printf : " << s << endl;}
};class student : public person
{
public:student():person(){}void printf(){ cout << "This is student no parameter printf!" << endl; }
};int main(void)
{student s;s.printf();//正確,輸出 This is student no parameter printf!
// s.printf("Hello World!"); //報錯,“school::printf”: 函數不接受 1 個參數//因為子類將父類所有的printf函數都屏蔽刪除了,包括printf(string s);
}
類成員函數重載
重載函數需要注意兩點
1.必須個數或對應位置參數至少有一項不相同 |
2.僅僅返回值不同不能作為重載判斷依據 |
class A
{
public:void printf(int a){ cout << "a: " << a << endl; }
// int printf(int a){ cout << "a:" << a << endl; }//報錯, 重載函數與“void A::printf(int)”只是在返回類型上不同void printf(string s) { cout << "s : " << s << endl; }//正確,與第一個printf參數類型不同void printf(string s, int a) { cout << "s : " << s << " a : " << a << endl; }//正確,與上一個printf參數個數不同void printf(int a, string s) { cout << "a : " << a << " s : " << s << endl; } //正確,與上一條printf對應位置的參數類型不同
};