c++ 学习笔记

  • 1. Never Return a Pointer to a Local Object
  • 2. Function Declarations Go in Header Files

It may be temptingand would be legalto put a function declaration directly in each source file that uses the function. The problem with this approach is that it is tedious and error-prone. By putting function declarations into header files, we can ensure that all the declarations for a given function agree. If the interface to the function changes, only one declaration must be changed.

  • 3. Constraints on Specifying Default Arguments

Specify default argument(s) in either the function definition or declaration. However, a parameter can have its default argument specified only once in a file. Default arguments ordinarily should be specified with the declaration for the function and placed in an appropriate header

  • 4. Unlike other function definitions, inlines should be defined in header files.
  • 5. Functions cannot be overloaded based only on differences in the return type.
  • 6. It is a bad idea to declare a function locally. Function declarations should go in header files.

If we declare a function locally, that function hides rather than overloads the same function declared in an outer scope. As a consequence, declarations for every version of an overloaded function must appear in the same scope.

void print(const string &);
void print(double);   // overloads the print function
void fooBar(int ival)
  void print(int);   // new scope: hides previous instances of print
  print("Value: ");  // error: print(const string &) is hidden
  print(ival); // ok: print(int) is visible
  print(3.14); // ok: calls print(int); print(double) is hidden

  • 7. No Copy or Assign for IO Objects
  • cannot have a vector (or other container) that holds stream objects.
  • cannot have a parameter or return type that is one of the stream types. If we need to pass or return an IO object, it must be passed or returned as a pointer or reference:
  • 8. IO => Buffers Are Not Flushed if the Program Crashes

Flushing the Output Buffer

cout << "hi!" << flush;      // flushes the buffer; adds no data
cout << "hi!" << ends;       // inserts a null, then flushes the buffer
cout << "hi!" << endl;       // inserts a newline, then flushes the buffer
  • 9. When we copy one container into another, the types must match exactly: The container type and element type must be the same.
  • 10. Containers of Containers
vector< vector<string> > lines; // ok: space required between close >
vector< vector<string>> lines; // error: >> treated as shift operator

  • 11. >, >=, <, <= Supported only for vector and deque‘s iterator.

The reason that only vector and deque support the relational operators is that only vector and deque offer fast, random access to their elements. These containers are guaranteed to let us efficiently jump directly to an element given its position in the container. Because these containers support random access by position, it is possible for their iterators to efficiently implement the arithmetic and relational operations.

  • 12. Container Elements Are Copies

When we add an element to a container, we do so by copying the element value into the container. Similarly, when we initialize a container by providing a range of elements, the new container contains copies of the original range of elements. There is no relationship between the element in the container and the value from which it was copied. Subsequent changes to the element in the container have no effect on the value that was copied, and vice versa.

  • 13. we can think of a constructor as executing in two phases: (1) the initialization phase and (2) a general computation phase
         Sales_item::Sales_item(const string &book)
             isbn = book;
             units_sold = 0;
             revenue = 0.0;

    This constructor assigns, but does not explicitly initialize, the members of class Sales_item. Regardless of the lack of an explicit initializer, the isbn member is initialized before the constructor is executed. This constructor implicitly uses the default string constructor to initialize isbn. When the body of the constructor is executed, the isbn member already has a value. That value is overwritten by the assignment inside the constructor body.

    • 14. 不能在类声明中初始化const数据成员。以下用法是错误的,因为类的对象未被创建时,编译器不知道SIZE的值是什么。

    class A


        const int SIZE = 100;     // 错误,企图在类声明中初始化const数据成员

        int array[SIZE];              // 错误,未知的SIZE



    class A


        A(int size);      // 构造函数

        const int SIZE ;


    A::A(int size) : SIZE(size)    // 构造函数的初始化表




    A  a(100); // 对象 a 的SIZE值为100

    A  b(200); // 对象 b 的SIZE值为200


    class A


        enum { SIZE1 = 100, SIZE2 = 200}; // 枚举常量

        int array1[SIZE1]; 
        int array2[SIZE2];







    configure.ac:64: error: possibly undefined macro: AM_ICONV

          If this token and others are legitimate, please use m4_pattern_allow.

          See the Autoconf documentation.

    make: *** [configure] Error 1

    解决方法, 用下面的命令:

    ./configure --enable-m4_pattern_allow 

    Useful PHP Command line options


    Usage: php [options] [-f] <file> [--] [args...]
           php [options] -r <code> [--] [args...]
           php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
           php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
           php [options] -- [args...]
           php [options] -a
      -a               Run interactively
      -c <path>|<file> Look for php.ini file in this directory
      -n               No php.ini file will be used
      -d foo[=bar]     Define INI entry foo with value 'bar'
      -e               Generate extended information for debugger/profiler
      -f <file>        Parse and execute <file>.
      -h               This help
      -i               PHP information
      -l               Syntax check only (lint)
      -m               Show compiled in modules
      -r <code>        Run PHP <code> without using script tags <?..?>
      -B <begin_code>  Run PHP <begin_code> before processing input lines
      -R <code>        Run PHP <code> for every input line
      -F <file>        Parse and execute <file> for every input line
      -E <end_code>    Run PHP <end_code> after processing all input lines
      -H               Hide any passed arguments from external tools.
      -s               Display colour syntax highlighted source.
      -v               Version number
      -w               Display source with stripped comments and whitespace.
      -z <file>        Load Zend extension <file>.
      args...          Arguments passed to script. Use -- args when first argument
                       starts with - or script is read from stdin
      --ini            Show configuration file names
      --rf <name>      Show information about function <name>.
      --rc <name>      Show information about class <name>.
      --re <name>      Show information about extension <name>.
      --ri <name>      Show configuration for extension <name>.
    Detail Usage:
    • Telling PHP to execute a certain file
    $ php my_script.php
    $ php -f my_script.php
    • Pass the PHP code to execute directly on the command line
    $ php -r 'print_r(get_defined_constants());'
    • prints out the built in (and loaded) PHP and Zend modules
    • $ php -m
      [PHP Modules]

    const Objects Are Local to a File By Default

    When we define a nonconst variable at global scope, it is accessible throughout the program. We can define a nonconst variable in one file andassuming an appropriate declaration has been madecan use that variable in another file:

          // file_1.cc
          int counter;  // definition
          // file_2.cc
          extern int counter; // uses counter from file_1
          ++counter;          // increments counter defined in file_1

    Unlike other variables, unless otherwise specified, const variables declared at global scope are local to the file in which the object is defined. The variable exists in that file only and cannot be accessed by other files.

    We can make a const object accessible throughout the program by specifying that it is extern:

          // file_1.cc
          // defines and initializes a const that is accessible to other files
          extern const int bufSize = fcn();
          // file_2.cc
          extern const int bufSize; // uses bufSize from file_1
          // uses bufSize defined in file_1
          for (int index = 0; index != bufSize; ++index)
                // ...

    In this program, file_1.cc defines and initializes bufSize to the result returned from calling the function named fcn. The definition of bufSize is extern, meaning that bufSize can be used in other files. The declaration in file_2.cc is also made extern. In this case, the extern signifies that bufSize is a declaration and hence no initializer is provided.


    FTP的命令行格式为:ftp -v -d -i -n -g [主机名],其中
    .n etrc文件;
    2.$ macro-ame[args]:执行宏定义macro-name.
    4.append local-file[remote-file]:将本地文件追加到远程系统主机,若未指定远程系统文件名,则使用本地文件名。
    10.cd remote-dir:进入远程主机目录。
    12.chmod mode file-name:将远程主机文件file-name的存取方式设置为mode,如:chmod 777 a.out。
    15.delete remote-file:删除远程主机文件。
    16.debug[debug-value]:设置调试方式,显示发送至远程主机的每条命令,如:deb up 3,若设为0,表示取消debug。
    19.form format:将文件传输方式设置为format,缺省为file方式。
    20.get remote-file[local-file]:将远程主机的文件remote-file传至本地硬盘的local-file。
    23.help[cmd]:显示ftp内部命令cmd的帮助信息,如:help get。
    28.macdef macro-name:定义一个宏,遇到macdef下的空行时,宏定义结束。
    30.mdir remote-files local-file:与dir类似,但可指定多个远程文件,如:mdir *.o.*.zipoutfile
    31.mget remote-files:传输多个远程文件。
    32.mkdir dir-name:在远程主机中建一目录。
    33.mls remote-file local-file:同nlist,但可指定多个文件名。
    35.modtime file-name:显示远程主机文件的最后修改时间。
    36.mput local-file:将多个文件传输至远程主机。
    37.newer file-name:如果远程机中file-name的修改时间比本地硬盘同名文件的时间更近,则重传该文件。
    39.nmap[inpattern outpattern]:设置文件名映射机制,使得文件传输时,文件中的某些字符相互转换,如:nmap $1.$2.$3[$1,$2].[$2,$3],则传输文件a1.a2.a3时,文件名变为a1,a2。该命令特别适用于远程主机为非UNIX机的情况。
    40.ntrans[inchars[outchars]]:设置文件名字符的翻译机制,如ntrans 1R,则文件名LLL将变为RRR。
    41.open host[port]:建立指定ftp服务器连接,可指定连接端口。
    44.proxy ftp-cmd:在次要控制连接中,执行一条ftp命令,该命令允许连接两个ftp服务器,以在两个服务器间传输文件。第一条ftp命令必须为open,以首先建立两个服务器间的连接。
    45.put local-file[remote-file]:将本地文件local-file传送至远程主机。
    48.quote arg1,arg2…:将参数逐字发至远程ftp服务器,如:quote syst.
    49.recv remote-file[local-file]:同get。
    50.reget remote-file[local-file]:类似于get,但若local-file存在,则从上次传输中断处续传。
    55.restart marker:从指定的标志marker处,重新开始get或put,如:restart 130。
    56.rmdir dir-name:删除远程主机目录。
    58.send local-file[remote-file]:同put。
    60.site arg1,arg2…:将参数作为SITE命令逐字发送至远程ftp主机。
    61.size file-name:显示远程主机文件大小,如:site idle 7200。
    69.type[type-name]:设置文件传输类型为type-name,缺省为ascii,如:type binary,设置二进制传输方式。
    70.umask[newmask]:将远程服务器的缺省umask设置为newmask,如:umask 3。
    71.user user-name[password][account]:向远程主机表明自己的身份,需要口令时,必须输入口令,如:user anonymous my@email。