【发布时间】: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 &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.x 和 msgD.y 通过电线并正确重建。但是,我想更改它们的重构方式,而不修改 receive 方法。这可能吗?
【问题讨论】:
-
如果你不能修改
Parent,那么编译器甚至不应该让你定义Parent::operator Child&()。 -
@Brain - 是的,那是一个错误 - 我已经进行了相应的编辑。我实际上可以修改 Parent。
-
你需要修改重构,所以这样做。通常它被称为反序列化。或向我们展示它是如何完成的
标签: c++ inheritance casting downcast static-cast