1.1 程序实例
#include <iostream>
using namespace std;
const int ArSize = 40;
unsigned long left(unsigned long num, unsigned ct);
char * left(const char * str, int n = 1);
int main()
{
char * trip = "Hawaii!!";
unsigned long n = 12345678;
int i;
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;
}
char * left(const char * str, int n)
{
if(n < 0)
n = 0;
char * p = new char[n+1];
int i;
for(i = 0; i < n && str[i]; i++)
p[i] = str[i]; // copy character
while(i<=n)
p[i++] = '\0'; //set rest of string to '\0';
return p;
}
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned n = num;
if(ct == 0||num == 0)
return 0;
while(n/=10)
{
digits++; // 判断数字有几位
}
int times = digits - ct; //除的次数
if(digits > ct)
{
while(times --)
num /= 10;
return num;
}
else
return num;
}
1.2 程序说明
-
基本概念:
➢函数多态:函数多态是指通过重载形式使用多个同名但实际上不同的函数。
➢函数重载的关键在于:函数的参数列表。 -
何时使用函数重载?
仅当函数基本上执行相同的任务,但使用不同形式的数据时,才应使用函数重载。 -
编译器如何跟踪和区分函数的不同重载版本?
C++编译器使用一种叫做名称修饰(名称矫正)的方式,根据形式参数列表,生成新名称。
资料参考 C++ Primer Plus (第六版)中文版,仅学习使用