这一章还是对一些基础知识的普及,但是确实有很多是原来不知道的。
第二章 对象的创建及使用
1 语言的翻译过程
⑴解释器:解释器将源代码转化成一些动作(它可由多组机器指令构成)并执行这些动作
a(优点):从写代码到执行代码的转化几乎能立即完成,并且源代码总是现存的,所以一出错误解释器很容易支出
b(缺点):对于大型项目解释器语言有些局限性,解释器必须驻留内存以执行程序,给程序带来额外的开销
⑵编译器:编译器直接把源代码转化成汇编语言或机器指令,最终的结果是一个或多个机器代码文件。
编译过程:a:预处理器进行预处理操作b:第一遍编译,将源代码分解成晓得单元并把它们按树形结构组织起来,例“A+B”中的‘A’、’+‘和’B’就是语法分析树的叶子节点
c:第二遍编译:由代码生成器遍历语法分析树,把树的每个节点转化成汇编语言或机器代码。如果代码生成的是汇编语言,那么还必须用汇编器对其汇编。
连接器:把一组模块连接成一个可执行程序,操作系统可以装载并执行它。
⑶静态类型检查:在编译的第一遍完成。这是C++的主要特性。
2 函数的声明和定义:ODR(one-definition rule);
⑴ 变量声明:extern int a;//表示变量在文件以外定义,或在文件后面才定义。
⑵函数声明:extern int fun();//由于和普通声明没有区别,所以可以不用使用extern。
3 连接:
⑴连接器如何找到库文件:当C或C++要对函数和变量进行外部医用时,根据引用的情况,连接器会选择两种处理方法中的一种。
a:如果还未遇到这个函数或变量的定义,连接器会把他的表示法加到“未解析的引用列表中”;b:如果连接器遇到过函数或变量定义,那么这就是已解决的引用。
如果连接器在目标模块列表中没有找到函数或变量的定义,它将去查找库。库有某种索引方式,连接器不必到库里查找所有目标模块---只需要浏览索引。(仅仅是目标模块加入连接,而不是整个库)
⑵秘密附加模块:在创建一个C/C++可执行程序时连接器会秘密连接某些模块,其中之一是启动模块,它包含了对程序的初始化例程,初始化例程是开始执行C/C++程序时必须首先执行的一段程序,初始化例程建立对战,并初始化程序中的某些变量。连接器总是从标准库中调用的经过编译的“标准”函数,由于标准库总是可以被找到,所以只需在程序中包含所需文件,就可以使用库中的任何模块。如果使用附加库,必须把库文件名添加到有连接器处理的列表文件中。
⑶尽可能的使用C++标准库:为了能够更好的移植我们的程序,尽量的使用C/C++标准库,万不得已也要使用符合POSIX标准的函数。
4 几个简单的小程序:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "call shell cmd:ifconfig" << endl;
system("server");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"copy file1.txt to file2.cpp"<<endl;
ifstream in("file1.txt");
ofstream out("file2.cpp");
string str;
while(getline(in,str))
{
out<<str<<"\n";
}
return 0;
}
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
cout<<"put the word in a vector"<<endl;
ifstream in("file1.txt");
string str;
vector<string> words;
while(in>>str)
{
words.push_back(str);
}
for(int i=0;i<words.size();i++)
{
cout<<words[i]<<"\n";
}
}
5根据这章学的编写了一个简单的文件管理器:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
system("cls");
cout<<"**************************************************************"<<endl;
cout<<"**************************************************************"<<endl;
cout<<"*************************FileConsole**************************"<<endl;
cout<<"**************************************************************"<<endl;
cout<<"**************************************************************"<<endl;
string strCmd;
cout<<"please input command:";
while(cin>>strCmd)
{
if(!strCmd.compare("copy"))
{
int words=0;
string strSrc;
cout<<"please input the name of source file:";
cin>>strSrc;
ifstream in(strSrc.c_str());
string strDes;
cout<<"please input the name of destination file:";
cin>>strDes;
ofstream out(strDes.c_str());
string strWord;
while(in>>strWord)
{
out<<strWord<<endl;
words++;
}
cout<<"copy finished"<<endl;
cout<<words<<"words have copied"<<endl;
}
else if(!strCmd.compare("quit"))
{
return true;
}
else
{
cout<<"command is invalid"<<endl;
}
cout<<"please input command:";
}
return true;
}
之后再补充哈!