将子类对象传递给采用超类对象的函数

将子类对象传递给采用超类对象的函数

本文介绍了将子类对象传递给采用超类对象的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下代码:

class Event {
public:
    virtual void execute() {
        std::cout << "Event executed.";
    }
}

class SubEvent : public Event {
    void execute() {
        std::cout << "SubEvent executed.";
    }
}

void executeEvent(Event e) {
    e.execute();
}

int main(int argc, char ** argv) {
    SubEvent se;
    executeEvent(se);
}

执行时,程序输出事件已执行.",但我想执行SubEvent.我该怎么办?

When executed, the program outputs "Event executed.", but I want to execute SubEvent. How can I do that?

推荐答案

您正在按值传递Event.该函数获取其自己的参数副本,这是一个Event对象,而不是SubEvent.您可以通过传递参考来解决此问题:

You are passing the Event by value. The function gets its own copy of the argument, and this is an Event object, not a SubEvent. You can fix this by passing a reference:

void executeEvent(Event& e)
{//                    ^
  e.execute();
}

这称为 对象切片 .等效于此:

This is called object slicing. It is the equivalent of this:

SubEvent se;
Event e{se};
e.execute();

这篇关于将子类对象传递给采用超类对象的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 10:34