通过 NULL 类指针在 C++ 中调用类方法
可以使用 NULL 类指针来调用类方法。
注意 − 这是未定义的行为,不能保证程序的执行。实际结果取决于使用的编译器。
说明这一点的程序如下所示。
示例
#include <iostream>
using namespace std;
class Example {
public :
void func() {
cout << "The function is called through Null class pointer.";
}
};
int main() {
Example *p = NULL;
p->func();
return 0;
}输出
上述程序的输出如下。
The function is called through Null class pointer.
现在,让我们来理解上述程序。
类 Example 包含一个成员函数 func()。此函数显示“该函数通过 Null 类指针调用”。此代码段如下所示。
class Example {
public :
void func() {
cout << "The function is called through Null class pointer.";
}
};在函数 main() 中,创建类空指针 p。然后使用 p 调用 func()。此代码段如下所示。
int main() {
Example *p = NULL;
p->func();
return 0;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP