c++ - 理解指向设置为 NULL 的对象的指针的问题

标签 c++ class

任何人都可以解释将指向对象的指针设为 NULL 是什么意思吗?

当我们将一个对象的ptr赋值为NULL时,我们怎么还能访问成员函数呢?

class A
{
public:
    void print()
    {
        cout<<"Hello";
    }
}

int main()
{
    A * a;
    A* b = NULL;

    a->print();
    b->print();
}

编辑: 程序会崩溃吗? http://ideone.com/DudZ6

最佳答案

指针用于访问该对象的成员。如果您的函数不需要访问任何成员并且不是虚拟的,则它们实际上不使用该对象。该代码严格来说仍然是无效的,但不会崩溃。

如果您用打印“this”指针替换内容,它仍然可以工作,因为您没有取消引用它。

struct X { 
    void print() { 
        cout << "this pointer is " << this << endl; 
    } 
};

int main() {
    X *x;
    x->print(); // will print whatever was on the stack, ie, random garbage
    X *t = NULL;
    t->print(); // will print a null pointer
}

如果您添加一个成员变量并打印它,或者将函数设为虚函数(因此必须通过对象本身查找它),它会崩溃。

struct X { 
    virtual void print() { 
        cout << "Hello World" << endl; 
    } 
};

struct X2 { 
    int y;
    void print() { 
        cout << "y is " << y << endl; 
    } 
};

int main() {
    X *x = NULL;
    x->print(); // will crash on null pointer dereference
    X2 *x2 = NULL;
    x2->print(); // will crash on null pointer dereference
}

关于c++ - 理解指向设置为 NULL 的对象的指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855701/

相关文章:

c++ - 太阳光栅图像 : Why 1 byte row padding when width is odd?

c++ - c++ NULL assignment 赋值运算符

c++ - 如何使用本地类的友元功能?

c++ - 无法将 std::set_intersection 应用于具有公共(public)字段的不同类型的结构

c++ - 静态 opencv 在 arm Linux busybox 上找不到 USB 网络摄像头?

Xcode 基础 : Declare custom class with integer properties and use it in another class

java - 声明一堆相似变量的最少行数

php - PHP 中的可变变量类扩展——可能吗?

c++ - 在各种函数中使用 push_back 更新类对象的 vector

java - 可以从作为参数传递的类创建对象吗?