|
在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。您不能仅通过返回类型的不同来重载函数。
下面的实例中,同名函数 print() 被用于输出不同的数据类型:
实例
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "整数为: " << i << endl;
}
void print(double f) {
cout << "浮点数为: " << f << endl;
}
void print(char c[]) {
cout << "字符串为: " << c << endl;
}
};
int main(void)
{
printData pd;
// 输出整数
pd.print(5);
// 输出浮点数
pd.print(500.263);
// 输出字符串
char c[] = "Hello C++";
pd.print(c);
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
整数为: 5
浮点数为: 500.263
字符串为: Hello C++
Copyright ©2011-2014 bbs.06climate.com All Rights Reserved. Powered by Discuz! (京ICP-10201084)
本站信息均由会员发表,不代表气象家园立场,禁止在本站发表与国家法律相抵触言论