函数重载(多态):函数名相同,函数的特征标不同(函数的参数不同),返回值类型任意
案例:
按需返回整数的前n位和按需返回字符串的前n个字符,使用函数重载来实现,
对于整数的处理:先要知道函数的总位数,要前n位,故需要通过除10的次数为总位数-n即可
然后循环处理即可
对于字符串的处理:根据n值不同,函数返回值指针指向的字符串位数的不同,进而输出即可
实现代码:
#include<iostream>
using namespace std;
unsigned long left(unsigned long num, unsigned ct);
char* left(const char* str, int n = 1);
int main() {
const char* trip = "Huawei!";
unsigned long n = 5201314;
int i = 0;
char* temp;
for (int i = 1; i < 10; ++i) {
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete[]temp;
}
return 0;
}
unsigned long left(unsigned long num, unsigned ct) {
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0)
return 0;
while (n /= 10) {
digits++;
}
if (digits > ct) {
ct = digits - ct;
while (ct--) {
num /= 10;
}
return num;
}
else {
return num;
}
}
char* left(const char* str, int n) {
if (n < 0) {
n = 0;
}
char* p = new char[n + 1];
int i = 0;
for (i = 0; i < n && str[i]; ++i) {
p[i] = str[i];
}
while (i <= n) {
p[i++] = '\0';
}
return p;
}
运行结果: