为什么在 dynamic_cast 失败后非虚函数调用仍然成功?
Why non-virtual function call is successful even after dynamic_cast is failed?
下面是代码片段,
#include <iostream>
using namespace std;
class A
{
public:
void print() const
{
cout << "In A::print()\n";
}
virtual void show()
{
cout << "In A::show()\n";
}
};
class B : public A
{
public:
void print() const
{
cout << "In B::print()\n";
}
void show()
{
cout << "In B::show()\n";
}
};
int main() {
A* a = new A;
a->show();
a->print();
B* b = dynamic_cast<B*>(a);
cout << b << endl;
b->print();
b->show();
return 0;
}
这是我 运行 时的输出(我使用的是 Visual c++ 编译器),
In A::show()
In A::print()
00000000
In B::print()
and then program stops working ....
有两个问题,
1. Why/How 对函数 B::print()
的调用即使在 dynamic_cast
失败后仍然成功,因为 b
的值为 0,如输出所示?
- 为什么程序在调用
B::show()
时停止工作(假设
之前调用 B::print()
成功)?
不足为奇。
- b 为 NULL,因为动态转换失败
- b->print() 没问题。好吧,
this
是 NULL,但它从未在其主体中使用过。
- b->show() 失败。尽管它也没有显式使用
this
,它仍然需要一个虚拟方法 table 查找来确定正确的 subclass 方法地址。指向虚拟 table 的指针是 Bclass 的(隐藏)字段;由于 b 为 NULL,程序崩溃。
下面是代码片段,
#include <iostream>
using namespace std;
class A
{
public:
void print() const
{
cout << "In A::print()\n";
}
virtual void show()
{
cout << "In A::show()\n";
}
};
class B : public A
{
public:
void print() const
{
cout << "In B::print()\n";
}
void show()
{
cout << "In B::show()\n";
}
};
int main() {
A* a = new A;
a->show();
a->print();
B* b = dynamic_cast<B*>(a);
cout << b << endl;
b->print();
b->show();
return 0;
}
这是我 运行 时的输出(我使用的是 Visual c++ 编译器),
In A::show()
In A::print()
00000000
In B::print()
and then program stops working ....
有两个问题,
1. Why/How 对函数 B::print()
的调用即使在 dynamic_cast
失败后仍然成功,因为 b
的值为 0,如输出所示?
- 为什么程序在调用
B::show()
时停止工作(假设 之前调用B::print()
成功)?
不足为奇。
- b 为 NULL,因为动态转换失败
- b->print() 没问题。好吧,
this
是 NULL,但它从未在其主体中使用过。 - b->show() 失败。尽管它也没有显式使用
this
,它仍然需要一个虚拟方法 table 查找来确定正确的 subclass 方法地址。指向虚拟 table 的指针是 Bclass 的(隐藏)字段;由于 b 为 NULL,程序崩溃。