简体   繁体   English

向下转换和复制 const object

[英]Downcasting and copying a const object

My method receives an object as a parameter and it must be accepted as a base type (though it is sent as a Derived type).我的方法接收一个 object 作为参数,它必须被接受为基本类型(尽管它是作为派生类型发送的)。 I want to make a copy of this object AND down cast it to a derived type, so that I can call a method of the derived type (which modifies properties of the derived object).我想复制这个 object 并将其向下转换为派生类型,以便我可以调用派生类型的方法(它修改派生对象的属性)。

I've been messing with variations of dynamic_cast, but can't make the compiler happy, OR, it compiles and I get a sigABRT on the dynamic_cast line (as per below):我一直在搞乱 dynamic_cast 的变体,但不能让编译器满意,或者,它编译并且我在 dynamic_cast 行上得到一个 sigABRT(如下所示):

void mymethod(Base message) {
    if (message.messageType() == "D") {
        Derived& derivedMessage = dynamic_cast<Derived&>(message);
        Derived derivedCopy = derivedMessage;
        derivedCopy.derMethod();

In case it matters, mymethod is a Qt SLOT, which receives the signal across threads.如果它很重要,mymethod 是一个 Qt SLOT,它接收跨线程的信号。 I don't think one can (or at least safely) pass a pointer to an object across threads, which is why I'm passing by value.我认为不能(或至少安全地)跨线程传递指向 object 的指针,这就是我按值传递的原因。

 void mymethod(const Base message)

If you pass a parameter of type Base , then the type of the object is Base and not something else - ie it will never be an object of a derived type.如果您传递Base类型的参数,则 object 的类型是Base而不是其他类型 - 即它永远不会是派生类型的 object。

If you want to have runtime polymorphism, then you need to use indirection.如果你想拥有运行时多态性,那么你需要使用间接。 Typical solution is to pass a reference to a base class subobject:典型的解决方案是传递对基本 class 子对象的引用

void mymethod(const Base& message)

The referred base can be a subobject within any derived class.引用的基础可以是任何派生的 class 中的子对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM