转换为派生类型的替代方法 [英] alternative to casting to derived type

查看:67
本文介绍了转换为派生类型的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




如果这是小学,请原谅我。我似乎无法在任何地方找到

解决方案。


// foo()仅在派生中声明/定义

Base * base = new Derived();

((Derived *)base) - > foo();


鉴于我想要使用Base *;是唯一的解决方案吗?


-J

解决方案

jimmy写道:



如果这是基本的,请原谅我。我似乎无法在任何地方找到
解决方案。

// foo()仅在Derived中声明/定义
Base * base = new Derived(); < br(>((Derived *)base) - > foo();

鉴于我想使用Base *;铸造唯一的解决方案?




是的。但是,我再说一遍,不要使用C风格的演员阵容。使用dynamic_cast

或static_cast。


是的。但是,我再说一遍,不要使用C风格的演员阵容。使用dynamic_cast
或static_cast。


如果Base完全没有虚函数,
dynamic_cast可能无效。

static_cast是更好的替代。


ben


ben写道:

是。但是,我再说一遍,不要使用C风格的演员阵容。使用dynamic_cast
或static_cast。



如果Base根本没有虚函数,dynamic_cast可能无效。




但是在OP所处的情况下,基类

通常至少有一个虚函数:析构函数。


-

Karl Heinz Buchegger
kb******@gascad.at


Hi,

Please forgive me if this is elementary. I can''t seem to find the
solution anywhere.

// foo() is only declared/defined in Derived
Base* base = new Derived();
((Derived*)base)->foo();

Given that I would like to use a Base*; is casting the only solution?

-J

解决方案

jimmy wrote:

Hi,

Please forgive me if this is elementary. I can''t seem to find the
solution anywhere.

// foo() is only declared/defined in Derived
Base* base = new Derived();
((Derived*)base)->foo();

Given that I would like to use a Base*; is casting the only solution?



Yes. But don''t, I repeat, DON''T use C style casts for it. Use dynamic_cast
or static_cast.


Yes. But don''t, I repeat, DON''T use C style casts for it. Use dynamic_cast
or static_cast.



dynamic_cast may NOT work if Base has no virtual function at all.
static_cast is a better alternative.

ben


ben wrote:

Yes. But don''t, I repeat, DON''T use C style casts for it. Use dynamic_cast
or static_cast.



dynamic_cast may NOT work if Base has no virtual function at all.



But in situations like the one the OP is in, the Base class
usually has at least one virtual function: the destructor.

--
Karl Heinz Buchegger
kb******@gascad.at


这篇关于转换为派生类型的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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