运行时以下代码抛出异常而不是正确打印。我无法理解为什么虚拟覆盖在这里不起作用?
#include <iostream>
using namespace std;
struct Base {
virtual ~Base() = default;
virtual void print() const {
throw runtime_error("");
}
};
struct Foo : public Base {
void print() const override {
cout << "foo" << endl;
}
};
struct Bar : public Base {
void print() const override {
cout << "bar" << endl;
}
};
int main(int argc, char const *argv[]) {
vector<Base> l = {
Foo(),
Bar(),
};
for(const auto& x : l) {
x.print();
}
return 0;
}