贺老师的教学链接
第一个C++程序
#include <iostream> //包含头文件iostream using namespace std; //使用命名空间std int main( ) { cout<<"Hello World."<<endl; //输出结果 return 0; }结构体类型在定义变量时,其前struct可以省略
#include <iostream> using namespace std; struct student { int no; float math; }; int main( ) { int n; cin>>n; student wang; //C语言中,必须struct student wang wang.no=n; cin>>wang.math; cout<<wang.no<<" "<<wang.math<<endl; return 0; }新增作用域运算符 ::
#include <iostream> using namespace std; float a=2.4; // 全局变量a int main() { int a=8; // 局部变量a cout<<a<<endl; // a为局部变量 cout<<::a<<endl; // ::a表示全局变量a }std::,表明使用命名空间std中定义的标识符
#include <iostream> //这儿不写使用的命名空间 float a=2.4; int main() { int a=8; std::cout<<a<<std::endl; std::cout<<::a<<std::endl; }引用的简单使用
#include <iostream> #include <iomanip> using namespace std; int main( ) { int a=10; int &b=a; //声明引用类型变量要同时初始化 a=a*a; cout<<a<<" "<<b<<endl; b=b/5; cout<<b<<" "<<a<<endl; return 0; }增加引用类型,主要用于扩充函数传递数据功能
#include <iostream> using namespace std; void swap(int &a,int &b); int main( ) { int i,j; i=3,j=5; swap(i,j); cout<<"i="<<i<<" "<<"j="<<j<<endl; return 0; } void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; }常变量(constant variable)
#include<iostream> using namespace std; const int price = 30; int main ( ) { int num, total; num=10; total=num * price; cout<<"total="<<total<<endl; return 0; }符号常量(宏定义) vs.常变量
#include <iostream> using namespace std; #define PRICE 30 //不是语句,末尾不加分号 int main ( ) { int num, total; num=10; total=num * PRICE; cout<<"total="<<total<<endl; return 0; }C++的程序员更爱常变量
#include<iostream> using namespace std; const int price = 30; int main ( ) { int num, total; num=10; total=num * price; cout<<"total="<<total<<endl; return 0; } 相关资源:C 语言大全