Liny_@NotePad

沉迷ACG中

空指针也能调用对象成员函数。。

YOYO posted @ 2009年10月15日 05:57 in 【C/C++】 with tags this , 2423 阅读

这段代码能运行吗?

///////////////////////////////////////////////////////
//	CopyRight(c) 2009, YOYO, All Rights Reserved.
//	Author: LIN YiQian
//	Created: 2009/10/14
//	Describe: For Test ^^
///////////////////////////////////////////////////////
#include <iostream>
using namespace std;

class CTest
{
public:
	void print(const char* const pszMsg)
	{
		cout << pszMsg << endl;
	}
};

int main(void)
{
	CTest* pTest = NULL;
	pTest->print("hello world");

	return 0;
}

话说这是同学今天写了很神奇的代码的hello world版。
其实以前看过这种的 = =。原因是在这个print函数中并没有用到对象数据成员。

我们知道在C++中类成员对象函数会被翻译成void print(const char* const pszMsg, CTest* this),
如果在里面调用对象数据成员(假如这里有个private int 的m_nTemp),
执行cout << m_nTemp << endl实际上等价于cout << this->m_nTemp << endl。
这时才会报空指针异常。

而如果调用static数据成员或static函数,则根本不会调用this,即使是空指针也不会有影响。

具体就不研究了 = = 。。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter