Thinking again in C++(三)缺省参数的误区[1]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 cphj 的 blog

    爱死thinking in系列了,所以起了这个名字。本文的思想也部分来至于这套书,或参照对比,或深入挖掘,或补益拾慧,或有感而发,既包括thinking in c++,甚至也包括thinking in java。

                          thinking again in c++(三)缺省参数的误区

    关键字:c++,缺省参数,default argument,函数,function,构造器,constructor,误区

    使用缺省参数时应该注意避开下列几种误区。

    1.滥用缺省参数,损害代码的结构和可读性。
      void f(bool b=false)
      {
            if (b)
            {
                  file://code of open file
            }
            else
            {
                  file://code of close file
            }
      }
    打开文件和关闭文件在实现代码上没有什么共同点,把两个属于同一类别的函数误认为是实现机制相同,凭空捏造一个参数硬把它们凑在一块,没有什么好处!相反,谁能记得住f(true)代表打开,f()代表关闭呢?况且,f(false)、f()都可以关闭文件,如果调用者混合使用它们就会增加维护上的困难。这种情况下,写成两个独立的函数,非常清晰。
      void open()
      {
                  file://code of open file
      }
      void close()
      {
                  file://code of close file
      }
    推而广之,如下的做法也值得商榷。
      class cstring
      {
      private:
            char * pcdata;
      public:
            cstring(char * pc=null);
      };
      cstring::cstring(char * pc)
      {
            if (pc==null)
            {
                  pcdata=new char[1];
                  //...
            }
            else
            {
                  pcdata=new char[strlen(pc)+1];
                  //...
            }
      }
    这一个更具备迷惑性,“都是构造器嘛,当然写在一块喽。”有人说。非也!应当看到,无参构造器与带char *参数的构造器使用的代码完全分离,并且缺省参数值null在设置数据成员时没有任何作用。cstring()构造器应改写如下:
      class cstring
      {
      private:
            char * pcdata;
      public:
            cstring();
            cstring(char * pc);
      };
      cstring::cstring()
      {
            pcdata=new char[1];
            //...
      }
      cstring::cstring(char * pc)
      {
            pcdata=new char[strlen(pc)+1];
            //...
      }
    总结:

本文关键:C++,缺省参数,default argument,函数,function,构造器,constructor,误区
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top