【问题标题】:Overload a C++ reference cast (downcasting inheritance)重载 C++ 引用转换(向下转换继承)
【发布时间】:2018-02-28 18:04:23
【问题描述】:

是否可以在 C++ 中重载引用强制转换?

我的代码格式无法触及:

void someMethod(Parent& parentReference, ...){
    ...
    Child& child = static_cast<Child&>(parentReference);

(Child 类直接公开地继承自 Parent 类)

我想调整此演员表的行为 - 我可以修改 Child 类。
我试过像这样重载强制转换运算符:

Parent::operator Child&(){
    ...

但是这个方法永远不会被调用。

我开始怀疑这是否可能?

编辑
根据 R Sahu,我接近这种情况: https://timsong-cpp.github.io/cppwp/n3337/expr.static.cast#2

struct B { };
struct D : public B { };
D d;
B &br = d;

static_cast<D&>(br);            // produces lvalue to the original d object

除了简单地分配B &amp;br = d;br 作为参数进入方法,并且之前通过网络发送(作为 NML)。

这将是场景:

struct B { };
struct D : public B { 
   int a;
   int b
};

D d;
d.a = x;
d.b = y;

server.send(d); 

...

client.receive(msg);

receive(B& msg){

  D& msgD = static_cast<D&>(msg);

}

msgD.xmsgD.y 通过电线并正确重建。但是,我想更改它们的重构方式,而不修改 receive 方法。这可能吗?

【问题讨论】:

  • 如果你不能修改Parent,那么编译器甚至不应该让你定义Parent::operator Child&amp;()
  • @Brain - 是的,那是一个错误 - 我已经进行了相应的编辑。我实际上可以修改 Parent。
  • 你需要修改重构,所以这样做。通常它被称为反序列化。或向我们展示它是如何完成的

标签: c++ inheritance casting downcast static-cast


【解决方案1】:

给定类

struct Parent
{
};

struct Child : Parent
{
};

static_cast&lt;Child&amp;&gt; 不会使用用户定义的转换函数。

来自5.2.9 Static cast/2

“cv1 B”类型的左值,其中 B 是类类型,如果从“指向 D 的指针”进行有效的标准转换,则可以转换为类型“对 cv2 D 的引用”,其中 D 是从 B 派生的类” 指向“指向 B 的指针”存在,cv2 与 cv1 的 cv 限定相同或更高,并且 B 既不是 D 的虚拟基类也不是 D 的虚拟基类的基类。结果的类型为“cv2 D”。

然后在5.2.9 Static cast/45.2.9 Static cast/5 中有“否则”子句。

我对上面的解释是,由于ChildParent的子类型,所以上面的第4条和第5条不适用。

【讨论】:

  • Child child3 = static_cast&lt;Child&gt;(parent);怎么会打电话给Parent::operator Child&amp;(){...
  • @fatman,我稍微更新了答案。 static_cast&lt;Child&gt;static_cast&lt;Child&amp;&gt; 不同。
  • @R Sahu - 感谢您的回复 - 它帮助阐明了我正在尝试做的事情。我在上面的问题中添加了更多细节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
相关资源
最近更新 更多