#include <iostream>
using namespace std;
class Base
{
public:
void fun(){
cout<<"Base fun()\n";
}
void display(){
cout<<"Base display() function\n";
}
};
int main()
{
Base *b; //Just a pointer to a base class
b->fun(); //how we are able to access fun() here?
b->display(); //how we are able to access display() here?
return 0;
}
Base fun()
Base display() function
不! 你有的是一个未初始化的指针,这是一个非常糟糕的bug。
Base *b;
声明指向base
类的对象的指针。 指针是内存位置的地址。 当指针未初始化时,它包含一个地址,但您无法知道该地址是什么。 因此,如果您使用这个指针,就像在您的示例中一样,行为是未定义的。
最有可能的是指针包含不允许您访问的一部分内存的地址,运行您的代码将导致分段错误。 这其实是最好的情况。
在最坏的情况下,指针指向某个有效内存,该内存将被解释为base
类的对象。 然后,如果你修改那个内存,你就会破坏它,导致很难修复的错误。