C++ 函數多態

/* leftover.cpp
 * 函數重載(多態)的條件:
 * 1)函數名必須相同
 * 2)函數列表必須不同(個數不同、類型不同、參數列表順序不同)
 * 3)函數返回值可以相同也可以不相同
 * 4)僅僅返回類型不同,不足以成爲函數重載
 */

#include <iostream>
unsigned long left(unsigned long num, unsigned ct);
char * left(const char * str, int n = 1);

int main() {
	using namespace std;
	const char * trip = "Haweii!!"; // test value
	unsigned long n = 12345678; // test value
	int i;
	char * temp;

	for (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;
	for (i = 0; i < n && str[i]; i++)
		p[i] = str[i];
	while (i <= n)
		p[i++] = '\0';
	return p;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章