這是關於這個指針上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