如果創(chuàng)建兩個或多個成員(函數(shù))具有相同的名稱,但參數(shù)的數(shù)量或類型不同,則稱為C++重載。 在C++中,我們可以重載:
這是因為這些成員只有參數(shù)。
C++中的重載類型有:
在C++中,具有兩個或更多個具有相同名稱但參數(shù)不同的函數(shù)稱為函數(shù)重載。
函數(shù)重載的優(yōu)點是它增加了程序的可讀性,不需要為同一個函數(shù)操作功能使用不同的名稱。
C++函數(shù)重載示例
下面來看看看函數(shù)重載的簡單例子,修改了add()方法的參數(shù)數(shù)量。
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
執(zhí)行上面代碼,得到以下結果 -
30
55
操作符重載用于重載或重新定義C++中可用的大多數(shù)操作符。 它用于對用戶定義數(shù)據(jù)類型執(zhí)行操作。
運算符重載的優(yōu)點是對同一操作數(shù)執(zhí)行不同的操作。
C++操作符重載示例
下面來看看看在C++中運算符重載的簡單例子。 在本示例中,定義了void operator ++ ()運算符函數(shù)(在Test類內(nèi)部)。
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
執(zhí)行上面代碼,得到以下結果 -
The Count is: 10