函數(shù)重載
- 函數(shù)名可以相同, 提高復(fù)用性
函數(shù)重載的條件
- 同一個(gè)作用域下
- 函數(shù)名相同
- 函數(shù)參數(shù)不同
– 參數(shù)個(gè)數(shù)不同
– 參數(shù)順序不同
– 參數(shù)類型不同 - 不可以使用返回值作為重載的條件
code:
#include<iostream>
using namespace std;
void test()
{
cout << "void test()" << endl;
}
void test(int a)
{
cout << "void test(int a)" << endl;
}
void test(int a, float b)
{
cout << "void test(int a, float b)" << endl;
}
void test(float a, int b)
{
cout << "void test(float a, int b)" << endl;
}
void main()
{
test();
test(100);
test(100, 3.14);
test(3.14, 100);
system("pause");
}
result:
void test()
void test(int a)
void test(int a, float b)
void test(float a, int b)
函數(shù)重載注意事項(xiàng)
引用作為重載
- 參數(shù)可以分為const和非const。
code:
#include<iostream>
using namespace std;
void test(int &a)
{
cout << "void test(int &a)" << endl;
}
void test(const int& a)
{
cout << "void test(const int& a)" << endl;
}
void main()
{
int a = 10;
test(a);
test(10); // 當(dāng)執(zhí)行void test(int &a) 則為int &a=10,會(huì)出錯(cuò),const int& a=10,正常
system("pause");
}
result:
void test(int &a)
void test(const int& a)
函數(shù)重載遇到默認(rèn)參數(shù)
code:
#include<iostream>
using namespace std;
void test(int a, int b = 10)
{
cout << "void test(int a, int b = 10)" << endl;
}
void test(int a)
{
cout << "void test(int a)" << endl;
}
void main()
{
//test(666); // 報(bào)錯(cuò),不知道執(zhí)行哪一個(gè)
test(20, 30);
system("pause");
}
result:
void test(int a, int b = 10)
文章來源地址http://www.zghlxwxcb.cn/news/detail-661143.html
文章來源:http://www.zghlxwxcb.cn/news/detail-661143.html
到了這里,關(guān)于C++系列-函數(shù)重載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!