C++11新特性
1.基于范围的for循环
int main()
{
int ar[] = { 1,2,3,4,5,6,7,8,9 };
/*int n = sizeof(ar) / sizeof(ar[0]);
int* ip = nullptr;
for (int i = 0; i < n; i++)
{
cout << ar[i] << " ";
}
cout << endl;*/
一般格式
for (ElemType val : array)
{
...//循环体
}
for (int x : ar)
{
x += 10;
cout << x << " ";//1 2 3...
}
for (int &x : ar)
{
x += 10;
cout << x << " ";//11 12 13 ...
}
for (const auto& x : ar)
{
cout << x << " ";
}
return 0;
}
2.类型推导auto decltype
auto:auto定义的变量,可以根据初始化的值,在编译时推导出变量名的类型
int main()
{
auto x = 10; //
auto dx = 12.23;
auto ch = 'a';
//限制
auto x = 10;
const auto* xp = &x;
auto ip = &x;
auto* sp = &x,u;//error 必须有初始化
不能用于函数参数
不能用于定义数组
实例化模板时不能当模板参数
decltype 用于编译时推导一个表达式的类型 不初始化
int x = 10;
decltype(x++) y = 1;
cout << x << endl;//10
const int& x = 10;
decltype(x) j = 10; //j = const int&
return 0;
}
new delete 动态内存
c
/*int n = 10;
int* ip1 = (int*)malloc(sizeof(int));
int* ip2 = (int*)malloc(sizeof(int*)*n);
int* ip3 = (int*)calloc(n, sizeof(int));
ip2 = (int*)realloc(ip2, sizeof(int) * n * 2);
free(ip1);
ip1 = nullptr;
free(ip2);
ip2 = nullptr;
free(ip3);
ip3 = nullptr;*/
c++
int n = 10;
int* ip1 = new int(10);//=new int[10] ;//new可以初始化
int* ip2 = new int[n] {1,2,3,4,5,6};//连续申请十个整形空间
delete ip1;
ip1 = nullptr;
delete []ip2;
ip2 = nullptr;
new的函数化使用
int n = 10;
无法初始化 底层是malloc
int* p1 =(int *) ::operator new(sizeof(int));//需要自己计算size 返回值是无类型 所以要强转
int* p2 = (int*)::operator new(sizeof(int) * n);
::operator delete(p1);// = free
::operator delete[](p2);
区别
/*new和delete是运算符 malloc和free是函数
malloc申请内存空间时,手动计算所需大小,new只需类型名,自动计算大小
new可以初始化 malloc不行
malloc返回值为void* 接受时必须强转
malloc失败是 返回值是NULL 使用时必须判空
new失败时会抛出异常 所以要有捕获异常处理程序
*/
//名字空间域
namespace ypw
{
int g_max = 10;
int g_min = 0;
int my_add(int a, int b)
{
return a + b;
}
}
namespace Primer
{
double pi = 3.1415926;
double my_add(double a, double b)
{
return a + b;
}
namespace Matrix
{
char my_max(char b, char a)
{
return a > b ? a : b;
}
}
}
namespace ypw//同名进行合并
{
float pi = 3.14;
int m_sub(int a, int b)
{
return a - b;
}
}
使用using声明可只写一次限定修饰名
using声明以关键字using开头,后面是被限定修饰的名字空间成员名
将整个命名空间引入
using namespace ypw;
int main()
{
cout << pi << endl;//3.14
}
使用using将名字空间中成员引入
using ypw::pi;
using Primer::Matrix::my_max;
直接引用
int main()
{
//作用于限定符
int a = ypw::my_add(1, 2);
cout << a << endl;
Primer::Matrix::my_max(1, 2);
return 0;
}