您的位置:首页 > 编程语言 > C语言/C++

c++,new,delete,成员指针

2014-08-16 21:15 323 查看
new和delete用来申请动态内存空间,一定要配对使用

#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为0时这样写没问题,而且可以进行解引用,并且直接delete不用数组括号也行
string *p_new_string = new string
;//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;
}


成员地址,是相对于开始地址的相对偏移。

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐