第二章 对象的创建与使用

2017-02-23  本文已影响0人  意不适

简介:介绍一些C++语法和程序构造的概念

2.1 语言的翻译过程

2.1.1 解释器

解释器将源代码转化成一些动作并立即执行这些动作。

优点:一旦发现错误,解释器能很容易指出;较好的交互性;适于快速程序开发。

局限性:解释器必须驻留内存以执行程序

2.1.2 编译器

编译器直接把源代码转化成汇编或机器指令。最终得到一个或多个机器代码文件。

优点:编译后的程序小,运行速度快。某些语言(C语言)可以分段编译。

2.1.3 编译过程

预处理(预处理器)—>语法分析(编译器)—>全局优化(全局优化器)—>生成目标模块(编译器)—>连接成可执行程序(连接器)—>装载运行(OS)

C++使用静态类型检查(编译器在第一遍中完成),也可以不使用静态类型检查,需要自己做动态类型检查。

2.2 分段编译工具

2.2.1 声明与定义

声明:向编译器介绍名字——标识符。“这个函数或变量可以在某处找到”

定义:“在这里建立变量或函数”

可以有多处声明,但只能有一个定义(ODR, one-definition rule)。

对于带空参数表的函数,C语言中表示:一个可以带任意参数(任意数目,任意类型)的函数

C++语言中表示:不带参数的函数

在变量定义前加 extern 关键字表示声明一个变量但不定义它

头文件是一个含有某个库的外部生命函数和变量的文件。

2.2.2 连接

某些早期的连接器对目标文件和库文件只查找一起,所以他们的顺序就特别重要。

2.2.3 使用库文件

使用库必须:

1)包含库的头文件

2)使用库中的函数和变量

3)把库连接进可执行程序

2.3 编写第一个C++程序

预防名字冲突的关键字:namespace。库或程序中的每一个C++定义集被封装在一个名字空间中。

在C++中, main()总是返回int类型。

在每个文件的第一行都有一条注释,以注释符跟一个冒号开始“//:”,而最后一行是一“/:~”开始的注释,表示文件结束。

2.4 关于输入输出流

调用其他程序:

#include <iostream>

using namespace std;

int main() {

system("notepad.exe");

system("pause");

}

2.5 字符串简介

//:c02:HelloString.cpp

#include <iostream>

#include <string>

using namespace std;

int main() {

string s1, s2;

string s3 = "hello world.";

string s4("I am");

s2 = "Today";

s1 = s3 + " " + s4;

s1 += " 8 ";

cout << s1 + s2 + "!" << endl;

system("pause");

}

///:~

2.6 文件的读写

//:c02:Scopy.cpp

#include <iostream>

#include <string>

#include <fstream>

int main() {

ifstream in("Scopy.cpp");

ofstream out("Scopy3.cpp");

string s;

while (getline(in, s))

out << s << endl;

}

//:~

2.7 vector 简介

vector是一个模板(template),可以用于不同的类型。如: vector<string> vector<int>

///:c02:GetWords.cpp

// Break a file into whitespace-separated words

#include <iostream>

#include <fstream>

#include <string>

#include <vector>

using namespace std;

int main() {

vector<string> words;

ifstream in("GetWords.cpp");

string word;

while (in >> word) // get one word everytime from "GetWords.cpp"

words.push_back(word);

for (int i = 0; i < words.size(); i++)

cout << i << " " << words[i] << endl;

system("pause");

}

///:~

2.9 练习

2-7 cin.get()是保留回车在输入流队列中的,而cin是丢弃回车的。

上一篇 下一篇

猜你喜欢

热点阅读