【发布时间】:2012-09-27 17:26:35
【问题描述】:
我将 C++ 基类更改为 protected 继承,而我的 dynamic_cast(s) 停止工作。
为什么要将继承更改为protected 会更改dynamic_cast 的行为?
struct Base {
static Base *lookupDerived(); // Actually returns a Derived * object.
};
struct Derived : protected /* Switch this to public to get it working */ Base {
static void test() {
Base *base = lookupDerived();
if (dynamic_cast<Derived *>(base)) {
std::cout << "It worked (we must be using public inheritance)." << std::endl;
} else {
std::cout << "It failed (we must be using protected inheritance)." << std::endl;
}
};
【问题讨论】:
标签: c++ public protected dynamic-cast