C++动态绑定问题
问题是:
a) 下面的代码合法吗? (考虑到它在运行时崩溃)
b) 如果 gcc 或 MVC 在编译时显示任何编译器标志,则以下代码中存在潜在问题?
#include <iostream>
using namespace std;
class A
{
public:
void write(){ cout<<"A"; }
};
class B
{
public:
virtual void write(){ cout<<"B"; }
};
int main()
{
A *pa=(A*) new B();
pa->write();
B *pb=(B*) new A() ;
pb->write();
delete pa;
delete pb;
return 0;
}
谢谢!
The questions are:
a) Is the following code legal or not ? (considering it crashes at run-time)
b) If there is any compiler flag for gcc or MVC to show at compile time, a potential problem in the following code ?
#include <iostream>
using namespace std;
class A
{
public:
void write(){ cout<<"A"; }
};
class B
{
public:
virtual void write(){ cout<<"B"; }
};
int main()
{
A *pa=(A*) new B();
pa->write();
B *pb=(B*) new A() ;
pb->write();
delete pa;
delete pb;
return 0;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这是不合法的。
B
不是从A
派生的,反之亦然。像这样强制强制转换会导致未定义的行为。你告诉编译器“闭嘴,我知道我在做什么”,这会导致各种各样的麻烦。这是避免旧的 C 风格转换并使用 C++ 风格转换(static_cast
等)的原因之一。No, it's not legal.
B
doesn't derive fromA
, nor vice versa. Forcing a cast like this results in undefined behaviour. You're telling the compiler "shut up, I know what I'm doing", which leads to all sorts of trouble. This is one reason to avoid old C-style casts, and use C++-style casts instead (static_cast
, etc.).