C++初识
HelloWord
打开Visual Studio,创建新项目,左侧选择Visual C++
,选择空项目。
右键源文件,添加→新建项
编写一段helloWord代码
#include <iostream>
using namespace std;
int main()
{
cout << "hello word" << endl;
system("pause");
return 0;
}
main
是一个程序的入口,每个程序都必须有这么一个函数,有且仅有一个。
点击运行代码
变量、常量和关键字
单行注释: //描述信息
多行注释: /* 描述信息 */
变量的作用:给一段指定的内存空间起名,方便操作这段内存
语法 :数据类型 变量名 = 初始值;
#include <iostream>
using namespace std;
int main()
{
//变量创建的语法:数据类型 变量名 = 变量初始值
int a = 10;
cout << "a = " << a << endl;
system("pause");
return 0;
}
**常量的作用:**用于记录程序中不可更改的数据
C++定义常量的两种方式
- #define 宏常量:
#define 常量名 常量值
· 通常在文件上方定义,表示一个常量 - #const修饰的变量:
#const 数据类型 常量名 = 常量值
· 通常在变量定义前加关键字const,修饰该变量为常量,不可修改
关键字的作用:预先保留的单词(标识符)
*不要用关键字给变量或者常量起名称
*标识符只能由字母、数字、下划线组成
*第一个字符必须为字母或下划线
*标识符中字母区分大小写
数据类型
C++规定在创建一个变量或者常量时,必须要指定出相应的数据类型,否则无法给变量分配内存
整型
sizeof
实型(浮点型)
作用:用于表示小数
- 单精度float
- 双精度double
科学计数法
float f = 3e2 // f = 3*10^2
字符型
作用:字符型变量用于显示单个字符
语法: char ch = 'a'
#include <iostream>
using namespace std;
int main()
{
//字符型变量创建方式
char ch = 'a';
cout << ch << endl;
//字符型变量所占内存大小
cout << sizeof(char)<<endl;
// 字符型变量常见错误
// char ch2 = "b" 要用单引号
//char ch3 = 'abc' 单引号内只能有一个字符
//字符型变量对应的ASCII编码
cout << (int)ch << endl;
system("pause");
return 0;
}
字符串
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "runoob";
string str2 = "google";
string str3;
int len ;
// 复制 str1 到 str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// 连接 str1 和 str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// 连接后,str3 的总长度
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}