C++基本语法(一)

2018-09-28  本文已影响0人  Fighting_Sir

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

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

枚举类型

#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 WIDTH 10 //注意不加分号
#define HEIGHT 20
int main(){
    cout<<"面积="<<WIDTH*HEIGHT<<endl;
    system("pause");
    return 0;
}
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 f1=3.14; //自动推导类型,在C++11中已删除这一用法
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 修饰局部变量可以在函数调用之间保持局部变量的值。

上一篇 下一篇

猜你喜欢

热点阅读