《C++ primer》(4th)读书笔记(Part I Basic)

   本部分介绍一般语言都具有的基本特性。 

     Essentially all languages provide:

           Built-in data types such as integers, characters, and so forth

           Expressions and statements to manipulate values of these types
           Variables, which let us give names to the objects we use
           Control structures, such as if or while , that allow us to conditionally execute or repeat a set of actions
           Functions that let us abstract actions into callable units of computation

     Most modern programming languages supplement this basic set of features in two ways: They let programmers extend the language by defining their own data types, and they provide a set of library routines that define useful functions and data types not otherwise built into the language.

Chapter 2:Variables and basic types

2.1基本的built-in Type

      从内存的角度看,这些基本类型是与具体的机器硬件相关的。

          The C++ built-in types are closely tied to their representation in the computer's memory.

          The integers, int, short , and long , are allsigned by default. 

           在进行赋值或者转换时小心可能的溢出越界。

            By default, floating-point literals are type double 

2.2 Literal Constants

          Two string literals (or two wide string literals) that appear adjacent to one another and separated only by spaces, tabs, or newlines are            concatenated into a single new string literal.

           在最后加"\"可以使得字面字符串直接跨行连接。Putting a backslash as the last character on a linecauses that line and the next to be treated             as a single line.Note that the backslash must be the last thing on the line no comments or trailing blanks are allowed. Also, any leading spaces or               tabs on the subsequent lines are part of the literal. For this reason, the continuation lines of the long literal do not have the normal indentation.

2.3 Variables

             必须先定义(或声明?)再使用变量。we must define the type of a variable before we can use that variable in our programs.

             A variable provides us with named storage that our programs can manipulate.

            注意区分lvalue and rvalue的微妙。

           标示符命名规范: A variable name is normally written in lowercase letters.An identifier is given a mnemonic name.An identifier containing multiple words is written either with an underscore between each word or by capitalizing the first letter of each embedded word. 

           Most generally,an object is a region of memory that has a type. More specifically, evaluating an expression that is an lvalue yields an object.

            两种初始化方式:copy-initialization: =  , direct-initialization :(  ).  For built-in types, there is little difference between the direct and the copy forms of initialization.

         definition && Declaration:A definition of a variable allocates storage for the variable and may also specify an initial value
for the variable. There must be one and only one definition of a variable in a program.A declaration makes known the type and name of the variable to the program. A definition is also a declaration: When we define a variable, we declare its name and type. We can declare a
name without defining it by using the extern keyword. A declaration that is not also a definition consists of the object's name and its type preceded by the keywordextern :

            NOTE:  In C++ a variable must be defined exactly once and must be defined or declared before it is used.

          Scope:  NOTE :  It is usually a good idea to define an object near the point at which the object is first used.

2.4 const修饰符

                NOTE (important!):   const Objects Are Local to a File By Default.

               Nonconst variables are extern by default. To make a const variable accessible to other files we must explicitly specify that it is extern .

2.5 Reference&

        A reference serves as an alternative name for an object.A reference is a compound type that is defined by preceding a variable name by the & symbol. A compound type is a type that is defined in terms of another type.  All operations on a reference are actually operations on the underlying object to which the reference is bound

         A const reference is a reference that may refer to a const object:  const int ival = 1024; const int &refVal = ival; 

2.6 Typedef Names

             A typedef lets us define a synonym for a type:

2.7  Enumerations 

              An enumeration is defined using the enum keyword, followed by an optional enumeration name, and a comma-separated list of enumerators enclosed in braces.

          NOTE: Enumerators Are const Values

     Each enum defines a new type.    An object of enumeration type may be initialized or assigned only by one of its enumerators or by another object of the same enumeration type

2.8 Class Type

   对于一个类的设计,可以先考虑需要它完成那些功能(毕竟设计该类最终的目的就是为了外界使用它),然后再据此考虑需要用到那些数据类型,数据结构、相关的内部操作。Each class defines an interface and implementation . The interface consists of the operations that we expect code that uses the class to execute. The implementation typically includes the data needed by the class. 

        When we define a class, we usually begin by defining its interfacethe operations that the class will provide. From those operations we can then determine what data the class will require to accomplish its tasks and whether it will need to define any functions to support the implementation.


与struct的比较,struct中默认是public,class中默认为private:The only difference between a class defined with the class keyword or the struct keyword is the default access level: By default, members in a struct are public ; those in a class are private .

2.9 编写一个头文件

           “Proper use of header files can provide two benefits: All files are guaranteed to use the same declaration for a given entity; and should a declaration require change, only the header needs to be updated.”

                           Headers Are for Declarations, Not Definitions

Because headers are included in multiple source files, they should not contain definitions of variables or functions.

There are three exceptions to the rule that headers should not contain definitions: classes, const objects whose value is known at compile time, andinline functions are all defined in headers. These entities may be defined in more than one source file as long as the definitions in each file are exactly the same.

.   We must ensure that including a header file more than once does not cause multiple definitions of the classes and objects that the header file defines. A common way to make headers safe uses the preprocessor to define a header guard . The guard is used to avoid reprocessing the contents of a header file if the header has already been seen.

    #ifndefSALESITEM_H
    #define SALESITEM_H
    // Definition of  class and related functions of this head file goes here
   #endif

NOTE: Headers should have guards, even if they aren't included 
by another header. Header guards are trivial to write and can avoid mysterious compiler errors if the header subsequently is included more than once.

           Chapter 3  Library Types

        这部分主要是介绍了三种更加高级的数据Type,一个是C++自身增强了的String类(在<string>头文件中),另外两个是STL中的vector和bitset。这里还有学习方法上的暗示,即我们完全可以只根据提供给我们的编程接口而不必需要知道它的具体定义来使用标准库中的类型。

3.1  Namespace using 命名空间

对于每一个SL中的类型名称我们都需要加以声明

                    A Separate Using Declaration Is Required for Each Name

                                             using std::cin;
                                              using std::cout;
                                               using std::endl;

在我们自己的源代码中使用using可以很简便。但在头文件中由于可能需要被#include到其他文件中,所以一般不使用using,而是在需要处仍使用长的直接限制符:There is one case in which we should always use the fully qualified library names: inside header files.  

NOTE: In general, it is good practice for headers to define only what is strictly necessary.

3.2 string库

#include<string>

using std::string;


Reading an Unknown Number of string s可以采用

                            string word;
                                // read until end-of-file, writing each word to a new line
                             while (cin >> word)
                           cout << word << endl;

或者:

                     string line;
                                    // read line at time until end-of-file
                          while (getline(cin, line))
                                    cout << line << endl;
                             return 0;


       NOTE: Any variable used to store the result from the string size operation ought to be of typestring::size_type . It is particularly important not to assign the return from size to an int .  A variable used to index a string should have type string::size_type .

          NOTE: When mixing string s and string literals, at least one operand to each + operator must be of  string type:

C++兼容了C中的一些库,注意应该规范的使用新的头文件:The standard C headers names use the form name .h . The C++ versions of these headers are named c name the C++ versions remove the .h suffix and precede the name by the letter c . The c indicates that the header originally
comes from the C library. Hence, cctype has the same contents as ctype.h .That way names from the standard library are consistently found in the std namespace.

3.3 vector库

    Vector是一个重要的container。是class temple。

                    #include <vector>
                    using std::vector;

                     vector<int> ivec;  

最重要的特性是 vector S Grow Dynamically

NOTE:vector<int>::size_type ;  Adding Elements to a vector:    ivec.push_back(t )

C++ programmers tend to write loops using!= in preference to < as a matter of habit.  

 3.4  迭代器入门:

               vector<int>::iterator iter;

                          for (vector<int>::iterator iter = ivec.begin();  iter != ivec.end(); ++iter)
                                  *iter = 0;  // set element to which iter refers to 0

NOTE: Any operation that changes the size of a vector makes existing iterators invalid. For example, after calling push_back , you should not rely on the value of an iterator into the vector .


3.5 bitset Library

 #include <bitset>
     using std::bitset;

初始化方式:bitset<n> b;

                         bitset<n> b(s);等,这里的n代表bit个数。

(这里的这些最好在实际使用时结合library reference manual中的介绍、例子进一步的学习其用法。)

Chapter 4 Arrays and Points

          这章主要介绍数组和指针,这两种同样从C中继承来的类型。但作者显然对这两者的使用非常慎重,认为使用数组和指针是非常非常容易出错的,所以一般不要使用,而是使用vector、string这样的标准库!


Modern C++ programs should almost always use vector s and iterators in preference to the lower-level arrays and pointers. Well-designed programs use arrays and pointers only in the internals of class implementations where speed is essential.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值