C++ Primer 总结之Chap2 Variables and basic types

本章包含知识点:

  1. 常用类型大小及基本规律
  2. 常量表达式
  3. constextern关键字
  4. 头文件相关

  1. integeral types(整值类型 指int, char, bool,而整型特指int

  • define sizeof(machine word) = W
  • 1 byte = 8 bits
  • 1 word = 4 bytes(typically)
  • 2^15=32768 , 2^31=2147483648
  • (at least)实际上只规定了最小值,并无严格规定
type size(byte)
char 1
wchar_t 2
size_t 4
short 2 or W/2
int 4(2 at least) or W
long 4 on 32 and 8 on 64
float 4
double 8
long long 8
long double 8
  1. 注意,if(s<0)s=-s;不一定都能取到s的绝对值——当s是个有符号数且为最小值时,-s还是它自己,因为-s已经超出范围了,按照规则转换到范围内之后恰好还是原来的那个最小负数(max positive + 1 = min negative)。另外,这里的-也不是减号,而是一个一元取反操作符。

  2. If the value given to an object is out of its range, then if it’s an unsigned value, it would always be adjusted to be a non-negative number, it gets the remainder of the value modulo the range of that type; if it’s signed value, then usually the same way but not guranteed.

    unsigned short k1 = 32768 * 2;
    short k2 = -32769;//The range is 32678,it's 32678*2-32769
    cout << k1 << ' ' << k2;//0, 32767
    
  3. Literal integer constant:

    024;// octal
    0x14;// hexadecimal
    20;// decimal
    

Default type is int or long,但可加上后缀强制转换:
12u;// unsigned 12L;// long 12UL or 12LU;// unsigned long
【注意!!!】整数字面常量没有负数!常见的-1其实是一个表达式,取1的相反数,负号是一元取反操作符。-10u其实是4294967286,即10取反后为-10但又被调整到非负范围内(强制类型转换发生在最后)

  1. Floating-point literal constant:
    3.14e5 , 0E0 , .001f,大小写皆可,默认double,后缀f转单精度,后缀L转extended precision(极少用)

    • ‘a’ : char
    • L’a’:wchar_t
    • 字符可用'\ooo''\xddd'八和十六进制数字表示该字符,如’\115‘(‘M’)
  2. Chracter String Literals

    • an array of const char,可以退化为指向常量字符的指针
    • 自动加终止符(null character)
    • wide string literal前缀加L
    • 多个由空格类间隔分隔的字符串会自动连接成一个,这样就可以多行输出一个长句了,但若连接常字符串和宽字符串,it’s undefined. Putting a backslash as the last character on a line causes the line and the next to be treated as a single line. Any leading spaces or tabs on the subsequent lines are part of the literal.
      cout<<"This is "
            "a " "Hello "  "world\n";
      cout<<"This is a \
            Hello word\n";//More than one whitespace!
      
      
  3. Definitely, we should not rely on machine dependent behaviors, such as assume that the size of int is a fixed and known value like 4.

  4. copy-initialization uses the equal(=) symbol, direct-initialization places the initializer in parentheses.

  5. 全局变量不初始化默认为0,' ',NULL...

    • A definition of a variable allocates storage for the variable and may also initialize it——create it. 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.
    • Any variable used in more than one file requires declarations that are separate from the variable’s definition.
    extern int i;// declares but does not define i,
    			 // with a initializer become definition
    int i;//declares and defines i
         // Can't define a variable twice
    
  6. scope分为global, local, statement三种,在底层里可用同名覆盖上一层,甚至连类型都能改变。In a word, names can be redefined in an inner scope. But this may be confusing so we should also avoid it.

  7. const的意义:

    • readability,从不明意义的常量变为更易读的变量;
    • maintainability,修改的时候只要在定义处修改即可,方便很多。而且加上const不会被无意中修改掉
    • const变量默认是相对于文件local,即便你把它写在全局位置上。除非定义的时候用extern const int a=8;这样子,那就相当于可以被其他文件使用了。non-const variable的话,只要放在文件的全局位置上,然后在别的文件中用extern typeName variableName;即可获取~
  8. extern是一个关键字,它告诉编译器存在着一个变量或者一个函数,如果在当前编译语句的前面中没有找到相应的变量或者函数,也会在当前文件的后面或者其它文件中寻找该定义。这里的变量和函数当然是指各个文件的全局变量啦,因为它不可能连函数(包括main函数)内部都寻找的。

  9. 全局变量重名的话在各个文件单独编译时不出错,但在将多个文件连接在一起的时候,这些变量是互相可见的,亦即同名就会collide(这也是header里声明的变量必须加extern的原因。设若不加,则若有多个源文件包含了该头文件,那这变量的定义就出现了两次了,而且都是在全局变量的位置上,link的时候就出错了;另外,这里的互相可见是在link阶段,并不代表可以直接使用其他文件的全局变量,因为这样你压根过不了自己文件的编译,要用别人的全局变量还是得用extern

    • Reference is only an alias. It must be initialized by an object of the same type when created. And once created, there is no way to rebind it to another object.
    • const reference is a reference that may refer to a const object, which is not possible for a non-const reference. But it can also refer to a non-const object. What’s more, it can be initialized to an rvalue or an object of different but related(即可转换的) type.(实际上是构建了一个临时的相应类型的变量让reference指向该变量,由于read only所以可行)
    int val = 3;
    const int cVal = 4;
    int &a = val;
    int &b = cVal;//error
    const int &c = val;
    const int &d = cVal;
    c = 5;//error
    int &e = 8;//error
    const int &f = 33;//ok
    double dVal = 3.14;
    const int &g = dVal;//ok, because read-only, same as
    				    //int temp=dVal;const int &g=temp;
    
  10. typedef 定义类型的同义词,如

    typedef double wages;
    wages hourly,weekly;
    
  11. enum open_mode {input = 2, output, append = 3, other};

    The value assigned to enum should be a constant expression, which can be evaluated by compiler at compile time. enumerator is const. But an enum object is not const.

  12. When we define a class, we start by defining its interface——the operations that the class will provide. From these 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.

  13. 定义class记得要加分号,报错的cpp文件可能是因为它包含的头文件少了分号,记得检查。

  14. class 成员默认privatestruct成员默认publicclass这个关键字还用于定义模板参数,除此之外无差别。

  15. Headers normally contains class definition, extern varibale declaration, function declaration. Two benefits:

    1. Consistency, all files are guaranteed to use the same declaration for a given entity;
    2. Only the header needs to be updated when changes are needed.

    A header should logically belong together because it needs time to compile. And headers are for declarations, not definitions. Definitions should NOT occur in a header. e.g. extern int val = 10; double val;//wrong, both are definitions

    However, there are 3 exceptions when we can use definitions: class, const object whose value is known at compile time, inline functions. (const默认是local的,所以可以。如果初始化用到 constant expression,很多时候不存在内存消耗而是直接替换了;如果用函数来初始化的话,那就得把它放到源文件中防止函数被反复调用了,加上extern也可以共享)

  16. Header guard

    #ifndef HEADER_H
    #define HEADER_H
    //blablabla
    
    #endif
    

Reference : C++ Primer 4th edition(评注版)

你可能感兴趣的:(C++-Primer,c++-primer,tips,basic)