程序结构¶
我们在学习每一种编程语言时,都会先学习写一个hello world的demo程序,下面我们将从这个demo程序来窥探一下我们C++程序的程序结构
//方法一
#include <iostream>
int main(void)
{
int a=0;
std::cout << "hello world" << std::endl;
std::cin >> a;
std::cout << "a=" << a <<std::endl;
return 0;
}
//方法二
#include <iostream>
using std::cout;//声明iostream库里命令空间std中的cout
using std::endl;//声明iostream库里命令空间std中的endl
using std::cin;//声明iostream库里命令空间std中的cin
int main(void)
{
int a=0;
cout << "hello world" << endl;
cin >> a;
cout << "a=" << a <<endl;
return 0;
}
//方法三
#include <iostream>
using namespace std;//声明iostream库里的命令空间std
int main(void)
{
int a=0;
cout << "hello world" << endl;
cin >> a;
cout << "a=" << a << endl;
return 0;
}
上述示例中
std:指iostream库里的标准命令空间cout:指标准输出设备cin:指标准输入设备endl:指换行符
以上是输出hello world和接收输入的简单C++代码,继承了C的预处理指令、函数、语句、表达式、运算符、变量、数据类型、关键字、注释等基本语法,同时也拓展了相关语法:
- 头文件在被include包含预处理时,不需要加
.h后缀 - 声明定义变量时引入了
namespace命名空间的概念,明确指定变量的作用范围 <<、>>运算符通过运算符重载分别指定输出流方向和输入流方向
此处只是列举了C++对C的部分扩展,详细的扩展表如下: