一.new delete用法
int *p=new int[80];//通过new申请内存空间
int (*px)[10]=((int *)[10])p;
1.new只能分配线性内存。
2.基本数据类型可以直接delete,复杂的如,数组,对象数组应包含delete []p; delete只能释放一次,释放后指向一个安全的地址。
二.函数重载原理
1.函数重载根据,参数类型不同,顺序不同,与返回值无关。函数名委托代理,根据不同的参数委托不同的函数。
void go(int,int){}
void go(int,double){}
void go(double){}
#include<iostream>
#include<stdlib.h>
using namespace std;
void go(int a)
{
cout << a << endl;
}
void go(double a)
{
cout << a << endl;
}
void go(int a, int b)
{
cout << a << ' ' << b << endl;
}
void main()
{
void (*p1)(int) = go;
void (*p2)(double) = go;
void (*p3)(int, int) = go;
cout << p1 << endl;
cout << p2 << endl;
cout << p3 << endl;
system("pause");
}
2.函数的默认参数
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
void print(int c,int a = 1, int b = 3)//c语言不可以这样
{
cout << a <<b<<c<<endl;
}
void print(int d)
{
cout << d<<endl;
}
void main()
{
void (*p1)(int c,int a,int b) = print;
void (*p2)(int) = print;
p1(5,1,3);
p2(5);
system("pause");
}
三.auto类型
1.auto实现通用的传入接口,根据变量类型进行定义。
2.对于auto变量的类型可通过函数 typeid().name() 获得。
#include<iostream>
#include<stdlib.h>
void main()
{
double db = 10.9;
double *pdb = &db;
auto num = pdb;//通用传入接口
std::cout << typeid(db).name() << std::endl;//打印变量数据类型
std::cout << typeid(num).name() << std::endl;
std::cout << typeid(pdb).name() << std::endl;
//typeid(db).name() db2;
decltype(db) numA(10.8);//通用的备份接口
std::cout << sizeof( numA )<<' '<<numA<< std::endl;
system("pause");
}
3.auto用于for循环中进行数组读取
#include<iostream>
#include<stdio.h>
using namespace std;
void main()
{
auto num(10);
auto num1(10.9);
cout << num << ' ' << num1 << endl;
int num2[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (auto data : num2)//循环一维数组
{
cout << data << endl;
}
double db[2][5] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.10 };
for (auto data : db)
{
cout << data << endl;
for (int i=0;i < 5;i++)
{
cout << *(data + i) << endl;
}
}
getchar();
四.枚举类型enum
1.C语言中的enum类型不注重类型。
#include<stdio.h>
enum color { red=11, yellow, green, white };
void main1()
{
enum color color1;
color1 = red;// 不注重数据类型
color1 = 11;
printf("%d\n", red);
printf("%d\n",yellow);
printf("%d\n", green);
getchar();
}
2.C++中enum可以限定类型通过enum类型限定为char
#include<iostream>
#include<stdlib.h>
enum color:char{red,yellow,green,white};//限定枚举的数据类型
void main()
{
color mycolor(red);
color mycolor1(color::red);
//mycolor = 1;//fault错误的赋值方式,类型不匹配
//mycolor = 'A';
mycolor = color::yellow;
printf("%d,%c\n", red);
printf("%d,%c\n", yellow);
system("pause");
}