输入-输出
#include<iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a <<" "<< b << endl;
return 0;
}
命名空间
#include<iostream>
using namespace std;
namespace A
{
int a = 2;
};
namespace B
{
int a = 3;
};
using namespace A;
int main()
{
int a = 1;
cout << a << endl;
cout << A::a << endl;
cout << B::a << endl;
cout << ::a << endl;
return 0;
}
这里的“::”是作用域符号,其前面一般是类名称,后面一般是该类的成员名称,C++中为了避免不同的类有相同的成员名称而采用作用域的方式进行区分。
new-delete
#include<iostream>
using namespace std;
int main()
{
//new delete在堆区动态申请释放空间
int* p1 = new int[3] {1, 2, 3};
for (int i = 0; i < 3; i++)
{
cout << p1[i] << " " << endl;
}
delete[]p1; //[]不给内容
p1 = NULL;
int* p2 = new int(3); //括号中不写内容自动给0
cout << *p2 << endl;
delete p2;
p2 = NULL;
//C语言写法
int* p3 = (int*)malloc(sizeof(int));
*p3 = 1;
cout << *p3 << endl;
free(p3);
p3 = NULL;
return 0;
}
malloc-free与new-delete的区别:
1.malloc-free是函数,且需要头文件支持。new-delete是C++中的关键字,去掉头文件不会报错。
2.malloc申请空间需要计算大小(字节),返回void*,即泛型指针 多数情况下需要强转。new放类型,不需要计算大小,返回对应类型的地址 不需要强转。
3.new申请结构体,类对象空间时自动调用构造函数,delete自动调用析构函数。malloc-free不会自动调用构造函数和析构函数。
//整型指针
int** p1 = new int*;
delete p1;
p1 = NULL;
//数组指针
int(**p2)[3] = new (int(*)[3]);
delete p2;
p2 = NULL;
//指针数组
int** p3 = new int*[3]();
delete[]p3;
p3 = NULL;
//函数指针
void (**p4)(int) = new (void(*)(int));
//*p4 = &fun;
delete p4;
p4 = NULL;
//整型的二维数组
int(*p5)[2] = new int[3][2]{ {1,2},{3,4},{5,6} };//[2]表示带有两个成员的一维数组
delete[]p5;
p5 = NULL;
//自定义类型(结构体)
struct Node {};
Node* p6 = new Node;
delete p6;
p6 = NULL;