前置基本知识
本篇文章主要包含三大结构(顺序,选择,循环)前的一些语言通用的内容。
c++基本结构
#include <iostream>
using namespace std;
int main()
{
return 0;
}
首先,我们导入io流头文件,用于输入输出数据。在入门阶段输出为cout,输入为cin。然后,命名空间曝光,可以简单认为让整个程序认识后续使用的头文件中的函数 。然后定义一个入口函数就可以了,代表整个程序从这开始。
注释
C++中注释和C语言差不多,使用//来单行注释,/* */来多行注释。
一,变量
数据类型
整型(int) :整数,一般四个字节
浮点型(float) : 小数,一般四个字节
字符型(char) :单字符,一般一个字节
字符串型(string) :字符串,多个字符,字节不定
布尔型(bool) : 一般用于逻辑判断(true/false),一个字节。
声明变量
int a;
float b;
char c;
double e;
bool f;
string h;//string使用时要导入string头文件
//当然可以直接声明时直接初始化
int a = 1;
变量赋值
int a = 1;
//修改a的值
a = 2;//这就是变量赋值
变量大小
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(int) << endl;
cout << sizeof(short int) << endl;
cout << sizeof(long long int) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double) << endl;
cout << sizeof(char) << endl;
cout << sizeof(bool) << endl;
return 0;
}
二,常量
常量就是不会改变的值,比如圆周率,一年的月份等等。
宏常量
#define 常量名 值
#define PI 3.14
当后续程序使用PI时会自动替换成3.14。和去一个别名差不多。常量名一般使用大写字母。
const修饰
除了使用宏定义,我们可以使用const来修饰一个变量使其从变量变成常量,后续的赋值将会发生错误。
const 数据类型 变量名 = 值
const int a = 20;
三,标识符命名
C++命名规则
C++规定给标识符(变量、常量、函数、结构体、类等)命名时,必须遵守以下规则。
- 在名称中只能使用字母字符、数字和下划线;
- 名称的第一个字符不能是数字;
- 名称区分大写字符与小写字符;
- 不能将C++关键字用作名称;
- 以下划线和大写字母打头的名称被保留给编译器及其使用的资源使用,如果违反了这一规则,会导致行为的不确定性。
- C++对名称的长度没有限制,但有些平台可能有长度限制(64字符)。
C++提倡有一定含义的名称(望名知义)。
C++关键字
关键词也叫保留词,是C++预先保留的标识符。
asm |
do |
if |
return |
typedef |
auto |
double |
inline |
short |
typeid |
bool |
dynamic_cast |
int |
signed |
typename |
break |
else |
long |
sizeof |
union |
case |
enum |
mutable |
static |
unsigned |
catch |
explicit |
namespace |
static_cast |
using |
char |
export |
new |
struct |
virtual |
class |
extern |
operator |
switch |
void |
const |
false |
private |
template |
volatile |
const_cast |
float |
protected |
this |
wchar_t |
continue |
for< |