C++根本语法
C++基本语法
常量:数值不能改变的数量,变量是数值允许改变的量
#include "stdafx.h" #include <iostream> #include <string> using namespace std; struct Student{ string Name; int age; bool isBoy; }; void main(int argc, char* argv[]) { int ir=0; for(int i=1;i<=100;i++){ ir+=i; } cout<<"1~100的和为:"<<ir<<endl; }
上面的int ir=0中,ir为变量,0为常量。
整数类型:
char、short、int、long。整数可以使用unsigned进行修饰,也可以在数字后面加上U来修饰。
浮点类型:
浮点类型默认为double。
布尔类型:
只有true、false对应1和0
字符串类型:
一个字符串被存放在一个字符数组中。可以通过char*类型来访问一个字符串,
编译器会在字符串结尾添加’\0‘来标识字符串已经结束。
#include "stdafx.h" #include <iostream> #include <string> using namespace std; void main(){ //通过指针形式访问 char* str1="hello world"; /* 通过字符串数组访问,C++中的数组只能定义为【数组类型 数组名[]】的格式 */ char str2[]="hello china"; cout<<str1<<endl<<str2<<endl; }
枚举类型:
枚举用来修饰一组个数确定,数据不变的数据。例如一年中的月份数,每周的天数等。
枚举下标默认从0开始,也可以现式指定枚举的下标。
#include "stdafx.h" #include <string> #include <iostream> using namespace std; /* 定义枚举 格式如:【enum 枚举名称{属性1,属性2...};】 */ enum Family_member{father=0,mother=1,yuxing=3}; void print_desc(Family_member member){ switch(member){ case father: cout<<"Father"<<endl; case mother: cout<<"mother"<<endl; case yuxing: cout<<"yuxing"<<endl; default: cout<<"I don't konw"<<endl; } } int main(int argc, char* argv[]) { for(int i=0;i<4;i++){ print_desc((Family_member)i); } }
结构类型:
和java中的类很相似,和类的区别在于结构体的成员在默认情况下都是公有的。
#include "stdafx.h" #include <string> #include <iostream> using namespace std; struct Student{ string name; int age; bool isBoy; }; void print_student(Student stu){ cout<<"姓名:"<<stu.name<<endl; cout<<"年龄"<<stu.age<<endl; cout<<"性别:"; if(stu.isBoy){ cout<<"男"<<endl; }else{ cout<<"女"<<endl; } } int main(int argc, char* argv[]) { Student stu; stu.age=24; stu.name="江雨行"; stu.isBoy=true; print_student(stu); return 0; }
数组类型:
数组类型用来描述一类数据类型的数据集合。
如果是静态数组,数组长度必须在编译之前指定好。
使用new来创建动态数组。数组下标从0开始。
数组的名称也可以理解成指向数组所在内存的指针。
#include "stdafx.h" #include <string> #include <iostream> using namespace std; /* void staticTest() { int i; cin>>i; //对于静态数组,不能运行时指定数组长度。 int a[i]; //报错 error C2133: 'a' : unknown size } */ /* void DynamicTest(){ int i; cin>>i; //通过new创建动态数组 int* a=new int[i]; delete[] a; }*/ void main(){ //C++中数组格式只支持 数组类型 数组名[]={}的格式 int m[]={1,2,3,4,5}; int length=sizeof(m)/sizeof(int); //数组下标从0开始 for(int i=0;i<length;i++){ m[i]++; } /* 这里不支持相同变量的重复编译,和编译器有关。 */ for(int j=0;j<length;j++){ cout<<m[j]<<endl; } cout<<"数组指针测试"<<endl; //将数组看成是指向数组所在内存的指针 int* p=m; for(int k=0;k<length;k++){ //取指针内容 cout<<*p<<endl; p++; } }