且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-12 12:57:40

您正在按值传递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();