zoukankan      html  css  js  c++  java
  • 第29课 类中的函数重载

    函数重载回顾:

    类中的重载:

    万变不离其宗:

    类中的普通成员函数和静态成员函数也够成重载。

    示例程序:

     1 #include <stdio.h>
     2 
     3 class Test
     4 {
     5     int i;
     6 public:
     7     Test()
     8     {
     9         printf("Test::Test()
    ");
    10         this->i = 0;
    11     }
    12     
    13     Test(int i)
    14     {
    15         printf("Test::Test(int i)
    ");
    16         this->i = i;
    17     }
    18     
    19     Test(const Test& obj)
    20     {
    21         printf("Test(const Test& obj)
    ");
    22         this->i = obj.i;
    23     }
    24     
    25     static void func()
    26     {
    27         printf("void Test::func()
    ");
    28     }
    29     
    30     void func(int i)
    31     {
    32         printf("void Test::func(int i), i = %d
    ", i);
    33     }
    34     
    35     int getI()
    36     {
    37         return i;
    38     }
    39 };
    40 
    41 void func()
    42 {
    43     printf("void func()
    ");
    44 }
    45 
    46 void func(int i)
    47 {
    48     printf("void func(int i), i = %d
    ", i);
    49 }
    50 
    51 int main()
    52 {
    53     func();
    54     func(1);
    55     
    56     Test t;        // Test::Test()
    57     Test t1(1);    // Test::Test(int i)
    58     Test t2(t1);   // Test(const Test& obj)
    59     
    60     func();        // void func()
    61     Test::func();  // void Test::func()
    62     
    63     func(2);       // void func(int i), i = 2;
    64     t1.func(2);    // void Test::func(int i), i = 2
    65     t1.func();     // void Test::func()
    66     
    67     return 0;
    68 }

    运行结果如下:

     深度的意义:

    重载的意义分析:

     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 char* strcpy(char* buf, const char* str, unsigned int n)
     5 {
     6     return strncpy(buf, str, n);
     7 }
     8 
     9 int main()
    10 {
    11     const char* s = "D.T.Software";
    12     char buf[8] = {0};
    13     
    14     //strcpy(buf, s);
    15     strcpy(buf, s, sizeof(buf)-1);
    16     
    17     printf("%s
    ", buf);
    18     
    19     return 0;
    20 }

    strncpy实现的功能和strcpy差不多,但是又多了一个名字,导致容易记忆混乱,因此,我们采用strcpy重载的方式将strncpy封装起来。

    运行结果如下:

    意义在于:我们通过重载扩展了strcpy这个函数,使得它变成了三个参数。而我们不用再记strncpy这个函数名字。

    函数重载可以扩展库中已有的函数。

    思考:

    我们可以通过重载扩展加法的功能。

    小结:

     

  • 相关阅读:
    zabbix中文配置指南(转)-服务器监控
    Native Fullscreen JavaScript API (plus jQuery plugin)
    浅谈 HTML5 的 DOM Storage 机制 (转)
    How to Customize Server Header using NginX headers-more module
    编译安装nginx并修改版本头信息—参考实例
    nginx 去掉服务器版本和名称和nginx_status 状态说明
    修改NGINX版本名称为任意WEB SERVER
    php加速缓存Xcache的安装与配置
    nginx-rrd监控nginx访问数
    Egret3D初步笔记二 (Unity导出场景使用)
  • 原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9571319.html
Copyright © 2011-2022 走看看