C++

Hello,C++

1
2
3
4
5
6
7
8
#include <iostream>  // 预处理指令,包含iostream库。
using namespace std; // 使用 std 命名空间中的所有实体。

int main() {

cout << "Hello, C++" << endl; //输出字符串。
return 0;
}

关于using namespace std;

  在C++中,using namespace std; 这一行代码的作用是告诉编译器在本文件中使用std命名空间。std命名空间包含了标准库中所有的函数、对象和类型,例如coutcinstring等。
  具体来说,标准库中的所有元素都是在std命名空间中定义的。如果不使用using namespace std;,就需要在使用这些标准库元素时加上std::前缀。

C++关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
asm     auto    
bool break
case catch char class const const_cast continue
default delete do double dynamic_cast
else enum explicit export extern
false float for friend
goto if inline int long mutable
namespace new operate new operator
private protected public
register reinterpret_cast return
short signed sizeof static static_cast struct switch
template this throw true try typedef typeid typename
union unsigned using virtual void volatile wchar_t while

字符串

C++风格的字符串
C++ 标准库提供了 string 类类型

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;

int main() {
string str = "Hello C++";
cout<< str << endl;
return 0;
}
>>>
Hello C++

布尔类型

大小:1个字节
bool类型只有两个值

  • true:真,值为1
  • flase:假,值为0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <iostream>
    using namespace std;

    int main() {
    bool t= true;
    bool f= false;
    cout<< t<<endl;
    cout<< f<<endl;
    return 0;
    }
    >>>
    1
    0

内存分区模型

不同区域存放的数据,赋予不同的生命周期

代码区

存放函数体的二进制代码,由操作系统进行管理

全局区

存放全局变量、全局常量、静态变量、字符串常量,程序结束后由操作系统释放

栈区

由编译器自动分配释放,存放函数的参数值,局部变量

堆区

由程序员分配和释放,若程序员不释放,程序结束时由操作系统释放
利用new在堆区开辟内存,利用delete释放内存

动态内存

  • 为任意的数据类型动态分配内存
    new data_type
  • 释放内存
    delete pointer
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <iostream>
    using namespace std;


    int main() {
    int *pt = new int; //动态内存申请
    *pt = 20;
    cout << *pt <<endl;
    delete pt; // 释放
    return 0;
    }
    >>>
    20

标准库 iostream

操作符

  • <<:输出操作符,将数据写入输出操作流
  • >>:输入操作符,从输入流读取数据

标准输入输出cin/cout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
int age;
cout << "please input your age:" << endl;
cin >> age;
cout << "your age is :" << age << endl;
return 0;
}
>>>
please input your age:
21
your age is :21