1

是否可以在不创建任何不同于 C 的层次结构或新类的情况下抛出 bad_cast 异常?main() 不能编辑,唯一可以编辑的是C类。我也不能明确抛出 bad_cast 。

class C{
    private:
        ...

    public:
        void f(){
        ...
        }
};


int main () {
    C c;
    c.f();

}

提前致谢

4

2 回答 2

1

,你不能。

dynamic_cast仅适用于多态类类型,C++ 核心语言的任何内置类型都不是多态类类型。

因此,只要您不能定义任何新的多态类(也不能#include定义其他已经存在的多态类),或者不能调用确实看到这些定义的另一个函数(这可能应该被视为作弊),就有没有办法你可以得到一个bad_cast例外。

dynamic_cast此外,除了引发异常之外,没有核心语言结构std::bad_cast。所以你的问题的答案:

是否可以在不创建任何不同于 C 的层次结构或新类的情况下抛出 bad_cast 异常?

是“”。

于 2013-04-08T10:22:49.570 回答
0

main() 不能编辑,唯一可以编辑的是C类。我也不能明确抛出 bad_cast 。

给定这些约束,定义一个嵌套在内部的多态类C,并尝试将其转换为不相关的东西(例如它C自己):

class C{
    private:
        struct X {virtual ~X(){}};

    public:
        void f(){
            X x;
            dynamic_cast<C&>(x);
        }
};

int main () {
    C c;
    c.f();
}

请注意,这可能会发出编译器警告,因为它足够聪明,可以确定强制转换永远不会成功。

If you also include the constraint that you can't make any new classes, then it's impossible. bad_cast is only thrown by the language itself when using dynamic_cast; that can only be applied to polymorphic types, and there are no polymorphic types available.

于 2013-04-08T11:08:24.080 回答