通过NULL类指针调用类方法 [英] Calling class method through NULL class pointer

查看:110
本文介绍了通过NULL类指针调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段:

class ABC{
public:
        int a;
        void print(){cout<<"hello"<<endl;}
};

int main(){
        ABC *ptr = NULL:
        ptr->print();
        return 0;
}

它运行成功。有人可以解释一下吗?

It runs successfully. Can someone explain it?

推荐答案

(我不记得我有这个知识, )

(I can't recall where I've got this knowledge, so I could be completely wrong)

底层下大多数编译器会将你的类转换为如下所示:

Under the hood most compilers will transform your class to somthing like this:

struct _ABC_data{  
    int a ;  
};  
// table of member functions 
void _abc_print( _ABC_data* this );  

其中_ABC_data是 C风格结构

where _ABC_data is a C-style struct

和您的调用 ptr-> print(); 将转换为:

_abc_print( NULL)

这是好的,因为你不使用参数。

which is alright while execution since you do not use this arg.

UPDATE:(感谢Windows程序员为右注释

这样的代码只适用于执行它的CPU。

没有理由利用这个实现功能。这是为什么:

UPDATE: (Thanks to Windows programmer for right comment)
Such code is alright only for CPU which executes it.
There is absolutely positively no sane reason to exploit this implementation feature. And here is why:


  1. 因为标准状态它产生未定义的行为(任何人都可以给一个链接或至少引用...)?)

  2. 如果您实际上需要调用成员函数而不使用实例,那么使用 static 关键字可以提供所有可移植性和编译时检查

  1. Because standard states it yields undefined behavior (could anyone give a link or at least reference(chapter N, par M...)?)
  2. If you actually need ability to call member function without instance, using static keyword gives you that with all the portability and compile-time checks

这篇关于通过NULL类指针调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆