1、一个简单的程序
#include <iostream> //iostream是头文件,用来说明要使用的对象的相关信息。
using namespace std; //使用命名空间,解决类重名的问题,不同的名字空间中的同名类不会引起程序错误。
int main() //主函数——执行一定的功能的模块,是程序执行的入口。一个C++程序有且只有一个主函数。
{
cout<<"Hello!\n"; //cout是输出流类的对象。
cout<<"Welcome to c++!\n";
} //输出“Hello!Welcome to C++!”
2、C++字符集
大小写英文字符,数字字符,某些特殊字符。
3、C++的词法记号
关键字 C++预定义的单词,不能用作别的含义
标识符 程序员定义的实体名称,变量名、函数名、类名等
文字 直接使用符号表示的变量
操作符 运算符号,+、-...
分隔符 用于分隔程序正文等 ,; {}等
空白符 空格、回车,tab、注释等产生的符号,C++不限制空白符的位置和数量
C++程序标识符以大小写或下划线开始,对大小写敏感。
4、变量和常量
#include <iostream>
using namespace std;
int main()
{
const int PRICE=30; //声明整型常量30,并给一个名字PRICE,在程序运行过程中不能改变。
int num,total; //声明整型变量,可以在程序运行过程中被概念。
float v ,r,h; //声明浮点型变量
num=10; //声明常量10,赋给变量num。
total=num*PRICE;
cout<<total <<endl;
r=2.5;
h=3.2;
v=3.14159*r*r*h; //r h默认为double类型,而v是float类型,会出错。因为double比float更精确。
cout<<v<<endl;
}
enum weekday{sun=7,mon=1,tue,wed,thu,fri,sat};
#include <iostream>
using namespace std;
enum game_result {WIN, LOSE, TIE, CANCEL};
int main()
{
game_result result; //声明变量时,可以不写关键字enum
enum game_result omit = CANCEL; //也可以在类型名前写enum
int count;
for (count = WIN ; count <= CANCEL ; count++)
{
result = (game_result)count; //整型值不能直接赋值给枚举变量,如果要赋值,需要进行强制类型转换。
if (result == omit)
{
cout << "The game was cancelled\n";
} //运行结果:The game was played and we won!
else The game was played and we lost.
{ The game was played
cout << "The game was played "; The game was cancelled
if (result == WIN)
cout << "and we won!";
if (result == LOSE)
cout << "and we lost.";
cout << "\n"; }}}
#include <iostream>
#include <iomanip>
using namespace std;
struct student //学生信息结构体
{
int num; //学号
char name[20]; //姓名
char sex; //性别
int age; //年龄
}stu={97001,"Lin Lin",‘F‘,19};//stu是结构体student的一个变量,这里是变量初始化
int main()
{ cout<<setw(7)<<stu.num<<setw(20)<<stu.name<<setw(3)<<stu.sex <<setw(3)<<stu.age;}
//运行结果: 97001 Lin Lin F 19
原文:https://www.cnblogs.com/lemaden/p/10237792.html