Dqsscha清华大学ACM集训队培训资料(内部使用).doc
文本预览下载声明
Time will pierce the surface or youth, will be on the beauty of the ditch dug a shallow groove ; Jane will eat rare!A born beauty, anything to escape his sickle sweep
.-- Shakespeare
清华大学ACM集训队培训资料(内部使用)
一、C++基础
基本知识
所有的C++程序都是有函数组成的, 函数又叫做子程序,且每个C++程序必须包含一个main函数,编译器(能够把源代码转换成目标代码的程序)把翻译后的目标代码和一些启动代码组合起来,生成可执行文件,main函数就是可执行文件的入口,所以,每个C++程序有且只有一个main函数。
下面我们看一个最简单C++程序。(程序1.1)
程序1.1
int main(){return 0;}
在这个程序中,如果缺少任何一个字符,编译器就无法将其翻译成机器代码。
此外,C++是对大小写敏感的,这就意味着,如果我将mian()函数拼为Main(),哪么,编译器在编译这段程序的时候就会出错。
编辑源文件
能够提共管理程序开发的所有步骤,包括编辑的程序成为集成开发环境(integrated development evironments, IDE)。在windows系统下,使用较为广泛的有Microsoft Visual C++、Dev-Cpp等,在UNIX系统下,有Vim、emacs、eclipes等。这些程序都能提供一个较好的开发平台,使我们能够方便的开发一个程序,接下我们所要了解的都是标准C++,所有源代码都在Dev-cpp下编写,能够编译通过。
如果我们修改程序1.1中的main()函数的名称,将其改为Main(),那么,IDE就会给出错误信息,比如“ [Linker error] undefined reference to `WinMain@16”,因为编译器没有找到main函数。
接下来,我们来看一个经典的C++例子(程序1.2)
程序1.2
#includeiostream
using namespace std;
int main(void)
{
coutHello Wrold!endl;
return 0;
}
运行结果
Hello World!
程序说明
第一行“#includeiostream”,是一句预处理命令,相当于把“iostream”这个文件的所有内容复制到当前位置,替换该行。因为在输出操作中需要做很多事,C++编译器就提供了很多已经写好的函数(成为C++标准库),我们做的只是拿来用就可以了。第二行的“using namespace std;”是使用标准命名空间,因为我们在程序中用到了在标准命名空间里的函数和对象。目前可以不了解其具体如何实现,在以后的程序设计中可以再对其进行了解。在明函数中“cout”Hello World!”endl;”是在屏幕上打印“Hello World!eHeH”,“endl”表明打印完这句话之后需要换行。如果我们替换引号内的内容,程序的输出就会相应改变。
另外一个C++程序例子
// ourfunc.cpp -- defining your own function
#include iostream
void simon(int); // function prototype for simon()
int main()
{
using namespace std;
simon(3); // call the simon() function
cout Pick an integer: ;
int count;
cin count;
simon(count); // call it again
cout Done! endl;
return 0;
}
void simon(int n) // define the simon() function
{
using namespace std;
cout Simon says touch your toes n times. endl;
} // void functions dont need return statements
下面试运行情况:
Simon says touch your toes 3 times.
Pick an integer: 512
Simon says touch your toes 512 times.
显示全部