一、基本语法
1. 程序结构
#include <iostream> //包含头文件
using namespace std; //使用std命名空间(编译器)
int main() // main() 是程序开始执行的地方
{
cout << "Hello World"; //输出 Hello World
return 0; //中止main函数
}
2. 数据类型:bool, char, int, float, double, void(无类型), wchar_t(宽字符串)
枚举类型enum color { red, green=5, blue } c //枚举名,标识符(red默认为0),枚举变量
3. 输入输出:cout<<‘name’ 用于向屏幕传送多个值,endl传入换行符
cin>>name>>age 需要用户依次输入并命名为name, age
4. typedef:typedef type newname //e.g. typedef int feet 定义一个新类型
5. 变量声明:int a, b; int func( ) { return 0; } //代码块中声明的为局部变量
definie或const定义常量: #define LENGTH 10 const int WIDTH = 5;
6. 左值:指向内存位置的表达式,可赋值
右值:指向内存某些地址的数值,不可赋值 e.g. int g = 20;
7. 字符串分隔可直接使用空格 e.g. "hello, " "d" "ear"
8. 存储类:auto自动变量声明(自动识别类型)e.g. auto f=3.14; auto s("hello");
register定义寄存器中变量 e.g. register int miles;
static定义程序生命周期内保存的变量 e.g. static int count = 10;
extern定义全局变量,可在多个文件间调用
9. 杂项运算符:sizeof返回变量大小
条件运算符 Condition ? X : Y
逗号表示连续运算e.g. j = 10; i = (j++,999+j);
成员运算符:点运算符引用对象strcpy(a.name, "zara")
箭头引用指针strcpy(p_a->name, "zara");
数据类型转换: double a = 21.09399; (int) a;
取地址运算&:var是变量时,&var为其地址
间接寻址*:返回地址指向的数据val = *ptr(ptr=&var)
10. 数学计算:x的y次方double pow(x, y);平方根double sqrt(x)
随机数:srand( (unsigned)time( NULL ) );//设置种子 j= rand();
11. 数组
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; balance[4] = 50.0;
多维数组int a[2][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} };
12. 字符串
char greeting[] = "Hello";
复制字符串strcpy(s1, s2),拼接strcat(s1, s2),长度strlen(s1)
String类:string str1 = "Hello";(str3 = str1; str3 = str1 + str2; len = str3.size();)
二、函数
1. 循环
①for循环:for (int &x : my_array){x *= 2;} , for( int a = 10; a < 20; a++ ){cout<<a;}
②while循环: while( a < 20 ){a++;}
2. 循环控制:break跳出当前循环,continue跳过当前循环的剩余部分
3. 判断
①if else语句:if(bool){……} else if(bool){……} else{……}
②switch语句:switch(grade){case ‘A’: cout << "很棒!" << endl; break;
case ‘B’: cout << "做得好" << endl; break; default :cout << "无效" << endl;}
4. 函数定义
return_type func_name( parameter list ){ body of the function}
e.g. int sum(int a, int b=20){ int result; result = a + b; return result; } result = sum(a, b)
三、面向对象
1. 结构typedef struct Books{ char title[50]; int book_id; } Books ; Books Book1;
2. 类class Box{ public: double length; double breadth;}