函数重载

  当函数基本上执行相同的任务, 但使用不同形式的数据时, 才应菜哦那个函数重载

 

#include <iostream>
#include <string>

using namespace std;


// 函数重载

unsigned long left(unsigned long sum, unsigned ct);
char * left(const char * str, int n = 1);


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;
}

int main(int argc, char const *argv []){
    char * trip = "Hawaii!";
    unsigned long n = 12345678;
    int i;
    char * temp;
    for (i = 1; i < 10; i++){
      std::cout << left(n, i) << '\n';
      temp = left(trip, i);
      std::cout << temp << '\n';
      delete [] temp;
    }
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-08
  • 2022-01-18
  • 2022-12-23
猜你喜欢
  • 2021-06-21
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-05-31
相关资源
相似解决方案