我Visual Studio 2003
用来编译和运行以下程序。
有 4 个赋值操作,我希望其中 2 个可以正常运行,其中 2 个会引发异常。重载内部有一个动态铸造= operator
,预计在不正确的交叉铸造期间会失败(从Apple
toOrange
或Orange
to铸造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 */
}