C++ Primer 读书笔记 - 第二章

1. 这章谈到了初始化和赋值其实是不同的,这使我想起了构造函数中的普通构造函数,拷贝构造函数,赋值构造函数,详见博文C++中的构造函数与析构函数 

    string这个类有default constructor,即初始化为"".

2. 一个变量在一个程序中能够声明多次,但只能定义一次。

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

4. There is no way to rebind a reference to a different object.

const int ival = 1024;
const int &refval = ival; //right
int &ref2 = ival; //wrong: nonconst reference to a const object
int i = 42;
// legal for const reference only
const int &r = 42;
const int &r2 = r + i;

5. class 和 struct不同点就是,class中的成员默认private,struct则默认public。

    发现在C++中,struct里面可以写函数

#include <iostream>
using namespace std;

typedef struct node {
    int a;
    int b;
    void print() { cout << "Hello world!" << endl; }
} node_t;

int main()
{
    node_t node;
    node.print();
    return 0;
}

6. Headers normally contain class definitions, extern variable declarations, and function declarations.

    Headers are for declarations, not definitions.

extern int ival = 10; // initializer, so it's a definition
double fica_rate;     // no extern, so it's a definition

    There are three exceptions to the rule that headers should not contain definitions: classes, const objects whose value if known at compile time, and inline functions.

7. Some const objects are defined in headers

    在C++程序中,对于一个变量,只能有一个定义(definition),定义意味着分配空间。对于const变量,他们只在所定义的文件中可见,所以可以把const变量的定义写在头文件中,包含这个头文件的所有文件分别有它们自己的const变量(名字和值都相同)。

    const变量如果是用常量表达式初始化的话,则所有的变量都有相同的值。许多编译器在编译期间就用常量表达式来替换之,所以也不会有任何存储空间由于存储常量表达式初始化的const变量。

    const变量如果不是用常量表达式初始化的话,则应该在源文件中定义并初始化,然后在头文件中添加extern声明,让其他文件共享

posted on 2013-05-19 10:27  NULL00  阅读(505)  评论(0编辑  收藏  举报

导航