[英]Types conversion between different types in an implicit manner
I need an in implicit conversion from A* to C*;我需要从 A* 到 C* 的隐式转换; i cannot change A's definition or implementation.我不能改变 A 的定义或实现。
class A
{
};
struct B: public A
{
};
struct C: public B
{
};
when i write the following:当我写以下内容时:
A* p;
C* q = p;
i am getting an error C2440;我收到错误 C2440; cannot convert from A* to C*.无法从 A* 转换为 C*。 what can i do giving the fact i cannot change A. both classes are plain structs of primitive data.鉴于我无法更改 A 的事实,我能做些什么。这两个类都是原始数据的简单结构。
The only way you can do this is to use a cast:您可以这样做的唯一方法是使用演员表:
// a C++ style static_cast:
C* q = static_cast<C*>(p);
// or the less verbose C-style cast
C* q = (C*)p;
Because C
is a derivative of A
and not every A
is a C
, it cannot be implicitly casted (like you could implicitly cast a C*
to an A*
because every C
is an A
(ie A
has "less or equal features" than C
, but not more)).因为C
是A
的导数,并且不是每个A
都是C
,所以它不能被隐式转换(就像你可以隐式地将C*
转换为A*
因为C
A
具有“不等于或等于 Aie A
C
,但仅此而已))。
I doubt that you really must have an implicit cast between pointer types.我怀疑你真的必须在指针类型之间进行隐式转换。 What is it making you think you do?是什么让你觉得你在做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.