这是关于这个指针上heap.Program如下分配对象的缺失,删除这个指针
class Sample{
private:
int m_value1;
int m_value2;
public:
Sample();
void setValues(int m_value1, int m_value2);
void display();
};
Sample::Sample(){
this->m_value1 = 0;
this->m_value2 = 0;
}
void Sample::setValues(int m_value1, int m_value2){
this->m_value1= m_value1;
this->m_value2 = m_value2;
display();
if(this != NULL)
{
cout <<"Deleting this pointer!"<<endl;
delete this;
cout <<"this->m_value1 is "<<this->m_value1<<endl;
cout <<"this->m_value2 is "<<this->m_value2<<endl;
}
}
void Sample::display(){
cout <<"Values are "<<this->m_value1<<" and "<<this->m_value2<<endl;
}
int main(){
Sample *obj1 = new Sample();;
obj1->setValues(4,6);
obj1->display();
getch();
}
OUTPUT:
Values are 4 and 6
Deleting this pointer!
this->m_value1 is 65535
this->m_value2 is 6
Values are 65535 and 6
为什么价值为m_value1消失,而它保持其他变量m_value2?
[相关](http://stackoverflow.com/a/7039749/220636) – nabulke 2012-02-13 11:31:38
也许你有学习'this'意义。所有的 – vulkanino 2012-02-13 11:32:36
首先,'this'永远不要向外界'NULL'非静态成员函数内部时。其次,你应该**永远不要删除'this'!你在做什么就像在拆下桥的时候拆掉它。 – 2012-02-13 11:33:11