c++ - 为什么在删除指针类后仍然可以调用指针类中的函数?

标签 c++ pointers function-pointers

<分区>

Possible Duplicate:
What will happen when I call a member function on a NULL object pointer?

#include <iostream>
#include <string>

using namespace std;

class myClass{
private:
        int *x, *y, *z;

public:
        myClass();
    ~myClass();
    void display();
    void math(int,int,int);
};


void myClass::math(int x,int y,int z){
    this->x = new int;
    this->y = new int;
    this->z = new int;

    *this->x = x;
    *this->y = y;
    *this->z = z;

    cout << "result: " << (x*y)+z << endl;
}

myClass::~myClass(){
    delete x;
    delete y;
    delete z;
}

void myClass::display(){
    cout << x << y << z << endl;
}

myClass::myClass(){
    x=0;
    y=0;
    z=0;
}


int main()
{
    myClass myclass;
    myClass *myptr;
    myptr = new myClass();

        myclass.math(1,1,1);

myptr->math(1,1,1);

delete myptr;

myptr->math(1,1,1);  **//why does this still print?**



int t;
cin >> t;

 }

:::OUTPUT:::

result: 2

result: 2

result: 2

我只是在 C++ 中闲逛,试图了解更多信息。我想看看 delete 运算符到底做了什么。为什么我在删除对象后仍然得到第三个结果“result: 2”?

最佳答案

对象内存可能还没有被其他东西覆盖。不要做这样的事情,这是未定义的行为

关于c++ - 为什么在删除指针类后仍然可以调用指针类中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206297/

相关文章:

c++ - header 中的编码与 cpp 中的编码 : different behaviour

php - 为什么在 C++ 中从十六进制字符串转换为 base36 字符串的结果与在 PHP 中相同操作的结果不同?

c++ - 对`i2c_smbus_read_word_data(int, unsigned char) 的 undefined reference

c++ - 有没有办法分解指向函数的模板化指针?

c++ - 为什么未指定 std::reverse_iterator::operator[] 的返回类型?

c++ - 在不更改函数中的对象时将对象或指针作为值传递

C++程序在随机位置无故停止

c - 用于抓取单个行和单个列的 2D 指针算法

c++ - 表达式 SFINAE 重载传递函数指针的类型

c - 将单指针和双指针传递给c中的函数