c++ primer 笔记[20190403]

232 阅读2分钟

P50

与其他变量不同,除非特别说明,在全局作用域声明的const变量是定义该对象的文件的局部变量。此变量只存在于那个 文件中,不能被其他文件访问。通过指定const变量为extern,就可以在整个程序中访问const对象。
换句话说,非const变量默认为extern。要使const变量能在其他的文件中访问,必须显式指定它为extern。详见下面的例子。

main.cpp 中全局变量bufsize

#include <iostream>
using namespace std;
 
extern void function();
int bufsize = 100;
 
int main()
{
    function();
    return 0;
}

function.cpp中声明了bufsize

#include <iostream>
using namespace std;
 
extern int bufsize;
 
void function()
{
    cout<<"function.cpp***bufsize----------"<<bufsize<<endl;
}

编译运行:

g++ -o main main.cpp function.cpp

./main

function.cpp***bufsize----------100
function.cpp能访问到main.cpp中bufsize

//////////////////////////////////现在我们将bufsize设置成const对象//////////////////////////// main.cpp

#include <iostream>
using namespace std;
 
extern void function();
const int bufsize = 100;
 
int main()
{
    function();
    return 0;
}

function.cpp内容不变

编译运行:

g++ -o main main.cpp function.cpp

/tmp/ccdvo28n.o: In function function()': function.cpp:(.text+0xb): undefined reference tobufsize' collect2: ld returned 1 exit status

function.cpp中bufsize没有定义。

只需要稍作改进main.cpp:

#include <iostream>
using namespace std;
 
extern void function();
extern const int bufsize = 100;
 
int main()
{
    function();
    return 0;
}

function.cpp不变

编译运行:

g++ -o main main.cpp function.cpp

./main

function.cpp***bufsize----------100 运行正常。

P52

const引用是指向const对象的引用!

const int val = 100;
const int &refval = val;   // ok both reference and object are const
int &ref2 = val;           // error: nonconst reference to a const object

P59

对于头文件不应该含有定义这一规则,有三个例外。头文件中可以定义类、值在编译时就已知道的const对象(数组的大小可以用const int型变量定义,这在C中是不行的),和inline函数。

const 变量默认是定义该变量的文件的局部变量。结合本专栏的第一条记录。
比如有一个头文件tmp.h如下:

const int watch = 100;

aaa.cpp如下:

#include "tmp.h"

int main()
{
	cout << add(3, 4) << endl;
	cout << "watch:" << watch << " addr:" << &watch << endl;
	return 0;
}

bbb.cpp如下:

#include <iostream>
#include "tmp.h"
using namespace std;

int add(int a, int b)
{
	cout << "watch:" << watch << " addr:" << &watch << endl;
	return a + b;
}

输出如下:

watch:100 addr:0084DDB8
7
watch:100 addr:0084DA10

这也说明了两个源文件的watch,变量的值相同,但地址不同,说明是两个变量。

P73

string对象有一个 string::size_type类型,具体解释:
string类类型和许多其他库类型都定义了一些配套类型,通过这些配套类型,库类型的使用就能与机器无关。size_type就是这些配套类型的一种。它定义为与unsigned型(unsigned int 或 unsigned long)具有相同的含义,而且可以保证足够大能够存储任意string对象的长度。因此,不要把size()的返回值赋给一个int变量,会导致溢出。