64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Box
{
public:
Box(int,int);
~Box();
void volume();
static int height;
int width;
int length;
};
Box::Box(int wi, int le)
{
width = wi;
length = le;
}
Box::~Box(){cout<<"the pointer is released."<<endl;}
void Box::volume()
{
cout<<height*width*length<<endl;
}
int Box::height = 100;
int main()
{
Box* p = new Box(10,20);
delete p;
cout<<p->height<<endl;
cout<<Box::height<<endl;
p->volume();
return 0;
}
class Box // 你的Box类
{
....
};
int main()
{
int ii[10] = { 2, 3, 4, 5, 6,7 , 8, 9, 10 };
void* p = &(ii[2]);
((Box*)p)->volume(); // (1)调用成员方法,输出2000(猜猜2000是怎么出来的?)。
p = NULL;
((Box*)p)->volume(); // 2、调用成员方法。
return 0;
}
当然了上述代码,执行时会有错误,但是编译时没有错误,而且是完全合法的。其中(1)执行成功,输出2000,(2)执行错误。执行错误是因为 NULL指向的地址是一块特殊的内存,运行环境和操作系统做了保护,如果p指向的是一块其它的内存,也有可能执行成功。
上述代码说明了一个问题,new、malloc只是声明一块内存是你的,你也可以不用声明,直接强制使用一块内存,只要你能预计可能的后果。
所以delete后的内存仍然是可以访问并操作的。