C++基本语法(一)

1、Hello World 程序结构

#include <iostream>
using namespace std;
int main(){
    cout<<"hello world"<<endl;
    return 0;
}

2、数据类型

C++提供了7种基本数据类型

类型
bool 1
char 1
int 4
float 4
double 8
void -
wchar_t 2或4

一些基本类型可以使用一个或多个类型修饰符进行修饰:

  • signed
  • unsigned
  • long
  • short

枚举类型

#include <iostream>
using namespace std;
enum color
{
    blue,
    red,
    white
}; //默认值从0开始
int main(){
    color c=red;
    cout<<c<<endl;
    system("pause");
    return 0;
}

3、变量类型

变量的声明&变量的定义

extern int b; //变量声明,编译时有用
int main(){
    int b=10;//变量定义
    cout<<b<<endl;
    system("pause");
    return 0;
}

4、常量定义

C++提供两种定义常量的方式:

  • 使用 #define 预处理器。
#define WIDTH 10 //注意不加分号
#define HEIGHT 20
int main(){
    cout<<"面积="<<WIDTH*HEIGHT<<endl;
    system("pause");
    return 0;
}
  • 使用 const 关键字。
const int HEIGHT=10;
const int WIDTH=20;
int main(){
    cout<<"面积="<<WIDTH*HEIGHT<<endl;
    system("pause");
    return 0;
}

5、存储类 (貌似没听说)

注意:C++ 11 开始,auto 关键字不再是 C++ 存储类说明符,且 register 关键字被弃用

  • auto存储类
auto f1=3.14; //自动推导类型,在C++11中已删除这一用法
  • register 存储类 (不懂)

    register 存储类用于定义存储在寄存器中而不是 RAM 中的局部变量。这意味着变量的最大尺寸等于寄存器的大小(通常是一个词),且不能对它应用一元的 '&' 运算符(因为它没有内存位置)。

  • static 存储类
using namespace std;

extern void fun();
int num=10;
int main(){
    
    while (num>0)
    {
        fun();
        num--;
    }

    system("pause");
    return 0;
}

void fun(){
    static int index=5; //程序的生命周期内保持局部变量的存在
    index++;
    cout<<"index="<<index<<endl;
    cout<<"count="<<num<<endl;
}
输出:
index=6
count=10
index=7
count=9
index=8
count=8
index=9
count=7
index=10
count=6
index=11
count=5
index=12
count=4
index=13
count=3
index=14
count=2
index=15
count=1

static 存储类指示编译器在程序的生命周期内保持局部变量的存在,而不需要在每次它进入和离开作用域时进行创建和销毁。因此,使用 static 修饰局部变量可以在函数调用之间保持局部变量的值。

  • extern 存储类
    extern 是程序使用未定义的变量或者方法来通过编译,链接程序的时候再将变量的定义和方法的定义链接过来。
  • mutable 存储类
    仅适用于类对象
  • thread_local 存储类
    使用 thread_local 说明符声明的变量仅可在它在其上创建的线程上访问。 变量在创建线程时创建,并在销毁线程时销毁。 每个线程都有其自己的变量副本。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容