0

Visual Studio 2003用来编译和运行以下程序。

有 4 个赋值操作,我希望其中 2 个可以正常运行,其中 2 个会引发异常。重载内部有一个动态铸造= operator,预计在不正确的交叉铸造期间会失败(从AppletoOrangeOrangeto铸造Apple)。但在我的情况下,所有 4 个操作都失败了(引发异常)。我已经运行了相同的代码Visual Studio 2008,它按预期工作正常。但是将整个项目迁移到Visual Studio 2008是很困难的。这是一个问题Visual Studio 2003吗?如果是这样,有没有办法解决这个问题?

注意:类Fruit是只读的,不能更改。

class Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
    }
};

class Apple : public Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
        Apple& apple = dynamic_cast<Apple&>( fruit );
    }
};

class Mango : public Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
        Mango& mango = dynamic_cast<Mango&>( fruit );
    }
};

int main( void )
{
    Apple apple;
    Mango mango;
    Fruit* fruit[] = { &apple, &mango };

    *fruit[0] = *fruit[0]; /* Expect to work ok */
    *fruit[0] = *fruit[1]; /* Expect an exception */
    *fruit[1] = *fruit[0]; /* Expect an exception */
    *fruit[1] = *fruit[1]; /* Expect to work ok */
}
4

1 回答 1

2

您需要检查Enable Run-time type information (RTTI)项目设置。类别“C++ 语言”。

至少在 VC6 中它不会默认启用。

于 2009-12-03T03:07:12.830 回答