我正在尝试使用C++,发现下面的代码非常奇怪.
class Foo{
public:
virtual void say_virtual_hi(){
std::cout << "Virtual Hi";
}
void say_hi()
{
std::cout << "Hi";
}
};
int main(int argc, char** argv)
{
Foo* foo = 0;
foo->say_hi(); // works well
foo->say_virtual_hi(); // will crash the app
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道虚方法调用崩溃,因为它需要vtable查找,并且只能使用有效对象.
我有以下问题
say_hiNULL指针?foo分配?有什么想法吗?
我接受了以下面试问题:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
Run Code Online (Sandbox Code Playgroud)
执行此代码时会发生什么,为什么?
我有以下代码片段:
class ABC{
public:
int a;
void print(){cout<<"hello"<<endl;}
};
int main(){
ABC *ptr = NULL:
ptr->print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它运行成功.有人可以解释一下吗?