简体   繁体   中英

Problem with cross casting in Visual Studio 2003

I am using Visual Studio 2003 to compile and run following program.

There are 4 assignment operation where I expect 2 of them to run ok and 2 of them to raise exception. There is a dynamic casting inside overloaded = operator which expect to fail during non proper cross casting (Casting from Apple to Orange or Orange to Apple ). But in my case all the 4 operations are failing ( Raising exception ). I have run the same code in Visual Studio 2008 and it is working fine as expected. But moving entire project to Visual Studio 2008 is difficult. Is this a problem of Visual Studio 2003 ? If so, is there any way to fix this?

Note: class Fruit is read only and cannot be changed.

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 */
}

You need to check Enable Run-time type information (RTTI) in Project Settings. Category "C++ Language".

In VC6 at least it will not be enabled by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM