new和delete用来申请动态内存空间,必定要配对使用ios
#include <string> #include <ctype.h> #include <vector> #include <iostream> #include <fstream> // using declarations states our intent to use these names from the namespace std using namespace std; int main() { int *p = static_cast<int*>(malloc(sizeof(int))); //对于内置类型,如int,double,float,char...即便不用new声明,使用delete释放也不会出任何编译,运行错误,可是对于任何类类型,无论是自定义仍是系统自带的,都会出错误
//队伍malloc分配后用delete释放,我进内存看过,能够正常的释放掉内存中的数据,彻底可行
int s = 1;
int *s = &s;
delete s; //飘红的这三行能够编译经过,运行也没问题,可是,调试的时候会出错,千万不要这样作!!! int *p_new = new int; //分配一个int类型的地址空间,不进行初始化 int *p_new_1 = new int(10);//初始化为10 int n = 10;//若是n过大,会致使内存申请失败抛出错误,若是不想抛出错误能够再new后面加上nothrow
//为何说是动态分配内存,由于n是变量,是不肯定的,因此每次分配的内存不肯定,是在运行时分配 char *p_new_array = new(nothrow) char[n];//对于内置类型,n为0时这样写没问题,并且能够进行解引用,而且直接delete不用数组括号也行 string *p_new_string = new string[n];//n为0时没法进行解引用,会报错,不加括号的delete出错,也不能进行解引用。 cout << *p << endl; cout << *p_new << endl; cout << *p_new_1 << endl; cout << *p_new_array << *(p_new_array+1) << endl; //delete p;// 基本内置类型能够,对于类类型这样不行,由于不是用new声明的 delete p_new;p_new=null;//将悬空指针变为空指针 delete p_new_1; p_new_1=null; delete p_new_array; p_new_array=null;//错误的写法,只对基本内置类型有效 delete[]p_new_string; //正确的写法,要和相应的new配对 return 0; }
成员地址,是相对于开始地址的相对偏移。c++
#include <string> #include <ctype.h> #include <vector> #include <iostream> #include <fstream> #include<new> // using declarations states our intent to use these names from the namespace std using namespace std; struct Date { int year; int month; int day; void print(){ cout << year << "-" << month << "-" << day << endl; } }; void showYear(Date a[], int length, int Date::*year); int main() { Date a[5] = { { 2001, 1, 1 }, { 2002, 2, 2 }, { 2003, 3, 3 }, { 2004, 4, 4 }, { 2005, 5, 5 } }; Date d = { 1997, 7, 9 }; cout << "&d = " << &d << endl; cout << "&d.year = " << &d.year << " &d.month = " << &d.month << " &d.day =" << &d.day << endl; //绝对地址 cout << &Date::year << &Date::month << &Date::day << endl;//成员地址打印出来是111,c++认为成员地址和函数地址无心义,因此都直接处理为true,在输出也就显示为1 //cout << static_cast<int*>(&Date::year) << endl; //那么,强转来看看地址,结果报错,不能转换 //匿名联合,两个变量同用同一个空间 union { int n; int Date::*mp; }; mp = &Date::day; cout << "n = " << n << endl;//输出8,相对于year的地址 //经过成员地址来访问结构中的成员 cout << d.*mp << endl; //应用,访问a数组中的,全部日期中的年份 showYear(a, sizeof(a)/sizeof(Date), &Date::year); //成员函数指针 d.print(); void (Date::*p)() = &Date::print; (d.*p)(); return 0; } void showYear(Date a[], int length, int Date::*p)//p是date中某个成员的地址,不可用day,year,month,会形成表达模糊 { for (int i = 0; i < length;++i) { cout << a[i].*p << " "; //a[i].year表达不出我想要用成员地址的意愿,由于year原本就是成员 //p是成员地址,*p是结构中的某个成员,a[i].*p,取出这个成员 } cout << endl; }