完整目录、平台简介、安装环境及版本:参考《21天学C++ 概览》
二、C++程序的组成部分
2.1 一个简单的程序
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
return 0;
}
- 预编译:#include<iostream>
- 程序开始时由操作系统调用: int main()
- 函数的开始位置:{
- 输出到屏幕: std::cout << “Hello World!\n”;
- 返回值:return 0;
- 函数结束标志:}
2.2 count简介
#include <iostream>
int main()
{
std::cout << "Hello there.\n";
std::cout << "Here is 5: " << 5 << "\n";
std::cout << "The manipulator std::endl ";
std::cout << "writes a new line to the screen.";
std::cout << std::endl;
std::cout << "Here is a very big number:\t" << 70000;
std::cout << std::endl;
std::cout << "Here is the sum of 8 and 5:\t";
std::cout << 8+5 << std::endl;
std::cout << "Here's a fraction:\t\t";
std::cout << (float) 5/8 << std::endl;
std::cout << "And a very very big number:\t";
std::cout << (double) 7000 * 7000 << std::endl;
std::cout << "Don't forget to replace Jesse Liberty ";
std::cout << "with your name...\n";
std::cout << "Jesse Liberty is a C++ programmer!\n";
return 0;
}
执行结果如下:
Hello there.
Here is 5: 5
The manipulator std::endl writes a new line to the screen.
Here is a very big number: 70000
Here is the sum of 8 and 5: 13
Here's a fraction: 0.625
And a very very big number: 4.9e+007
Don't forget to replace Jesse Liberty with your name...
Jesse Liberty is a C++ programmer!
请按任意键继续. . .
2.3 标准Namespace
2.3.1 告诉编译器使用标准库函数cout和endl
#include <iostream>
int main()
{
using std::cout;
using std::endl;
cout << "Hello there.\n";
return 0;
}
执行结果如下:
Hello there.
请按任意键继续. . .
2.3.2 使用全部namespace标准
#include <iostream>
int main()
{
using namespace std;
cout << "Hello there"<< endl;
return 0;
}
执行结果如下:
Hello there
请按任意键继续. . .
2.4 注释
2.4.1 注释类型
双斜杠//:标准C++行注释;
斜杠星/* */:C型注释,C++也兼容;
2.4.2 使用注释
函数名字首先应该易识别,见函数名知函数功能;
混乱难懂的代码不应通过注释来标明,而应该重新设计并重新编写以便更容易看懂;
先应将程序写好,然后借助注释使程序更清楚易懂;
规则1:注释不应该用来说明发生了什么事情,而应说明为什么会发生这种事情;
规则2:类似DLL或LIB这种对外提供接口服务的,需要详细说明函数功能、调用前后环境、每个参数具体类型及代表意义、返回值类型及意义。
2.5 函数
2.5.1 函数的组成:函数头(返回类型、函数名、参数)+函数体
#include <iostream>
int sum(int a, int b){
return a+b;
}
void nullval(){
std::cout<< " not return" <<std::endl;
}
int main(){
std::cout << sum(5, 6) <<std::endl;
nullval();
return 0;
}
执行结果如下:
11
not return
请按任意键继续. . .
- 函数的功能由语句实现:
- 如果使用return语句,则函数返回一个值并退出;
- 如果不使用return 语句,则函数在结束时自动返回空值。