为什么没有static_cast就失败? [英] Why does this fail without static_cast?

查看:243
本文介绍了为什么没有static_cast就失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译 有效,但编译 失败,并显示错误。



为什么会发生这种情况?

  A类{
public:
A(){}
};

class B:public A {
public:
B(){}
};

void f(){
A * a = new A();
B * b = static_cast< B *>(a);
}

void g(){
A * a = new A();
B * b = a;
}


解决方案

A static_cast 强制执行可能不安全的转化。

  B * b = static_cast< B * ;(一个); 

如果 a 指向一个 A 对象,实际上是 B 对象的基类子对象,但它不会。强制转换。

  B * b = a; 

这里没有转换,并且(正确)没有从基类指针到派生类的隐式转换类指针。指向一个派生类的指针总是可以转换为一个指向一个基类的指针,因为派生类对象总是包含一个基类子对象,但不是每个基类实例都是一个特定派生类类型的子对象。 p>

Compiling f works, but compiling g fails with an error.

Why does this happen?

class A {
public:
  A() {}
};

class B : public A {
public:
  B() {}
};

void f() {
  A* a = new A();
  B* b = static_cast<B*>(a);
}

void g() {
  A* a = new A();
  B* b = a;
}

解决方案

A static_cast forces a conversion that is potentially unsafe.

B* b = static_cast<B*>(a);

This would be valid if a pointed to an A object that actually was the base class sub-object of a B object, however it doesn't. The cast forces the conversion.

B* b = a;

There is no cast here and there is (correctly) no implicit conversion allowed from base class pointer to derived class pointer. A pointer to a derived class can always be converted to a pointer to a base class because a derived class object always contains a base class sub-object but not every base class instance is a sub-object of a particular derived class type.

这篇关于为什么没有static_cast就失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆