1.万物之源HelloWorld.
#include<iostream>
using namespace std;
void main(){
cout<<"Hello World!"<<endl; //endl为换行符
return 0;
}
命名空间:
using namespace std即为表明使用std命名空间,不用时则为std::cout<<"Hello World!"<<std::endl;
std::cout表明cout是定义在命名空间std中的。使用命名空间可避免无意中使用了与库中所定义名字相同的名字而引致冲突。
2.变量的声明和定义.
声明:用于向程序表明变量的类型和名字,不分配存储空间,可多次声明。可用extern声明,例:extern int i;
定义:用于为变量分配存储空间,还可为变量指定初始值,变量有且仅有一个定义。例:int i; 声明有初始值时被认为是定义,例:extern double pi=3.14;
3.变量作用域.
#include<iostream>
using namespace std;
int i=20; //全局变量
int main(){
cout<<i<<endl;
int i=10; //局部变量的值可以覆盖全局变量
cout<<i<<endl;
return 0;
}
输出结果为:
20
10
4.定义常量.
在C++中,有两种简单的定义常量的方式:
● #define预处理器
● const关键字
(1)#define预处理器
无数据类型,没有类型安全检查,只进行字符替换。
#include<iostream>
using namespace std;
#define length 10
#define width 5
#define newline '\n'
int main(){
cout<<length<<endl;
cout<<width<<endl;
cout<<newline<<endl;
int area;
area=length*width;
cout<<area;
cout<<newline;
return 0;
}
输出结果为:
10
5
50
(2)const关键字
有数据类型。
#include<iostream>
using namespace std;
int main(){
const int length=10;
const int width=5;
const char newline='\n'; //常量在定义后不能修改,故定义时必须初始化
int area;
area=length*width;
cout<<area;
cout<<newline;
return 0;
}
const对象默认为文件的局部变量,此变量只存在于那个文件中,不能被其他文件访问。
通过指定const变量为extern,即可在整个程序中访问const对象。
//file_1.cc
extern const int bufsize=fcn();
//file_2.cc
extern const int bufsize;
for(int index=0;index!=bufsize;++index)
......
●普通引用
#include<iostream>
using namespace std;
int main(){
int ival=1024;
int &reival=ival; //必须用与该引用同类型的对象初始化,只能用对象初始化,不能使用数字等
cout<<ival<<endl;
cout<<reival<<endl;
reival+=2; //引用只是它绑定对象的另一名字,作用在该引用上的所有操作均为作用在该引用绑定的对象上
cout<<ival<<endl;
cout<<reival<<endl;
return 0;
}
输出结果为:
1024
1024
1026
1026
●const引用
#include<iostream>
using namespace std;
int main(){
int ival=1024;
const int &reival=ival; //可以读取但不可修改reival
cout<<ival<<endl;
cout<<reival<<endl;
const int &i=1022;
const int &j=i+ival; //const引用可以初始化为不同类型的对象,或初始化为右值
cout<<i<<endl;
cout<<j<<endl;
return 0;
}
输出结果为:
1024
1024
1022
2046