【问题标题】:Problem with cross casting in Visual Studio 2003Visual Studio 2003 中的交叉转换问题
【发布时间】:2009-12-03 02:55:52
【问题描述】:

我正在使用Visual Studio 2003 编译并运行以下程序。

有 4 个赋值操作,我希望其中 2 个可以正常运行,其中 2 个会引发异常。在重载的= operator 内部有一个动态转换,预计在不正确的交叉转换期间会失败(从Apple 转换到OrangeOrangeApple)。但在我的情况下,所有 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 */
}

【问题讨论】:

  • 您确定在您的 VS 2003 项目设置中启用了 RTTI 吗?
  • 除了您的问题,您应该始终将赋值运算符的参数声明为 const&。即使它在没有 const 的情况下工作,用户也不会期望它写的分配的右手边有副作用(例如,你的 *fruit[0] = *fruit[1] could 以任何方式改变 *fruit[1] 处的对象): virtual void operator = ( const Fruit&fruit ) {..} 只有非 const 有意义的情况通常是某种“移动”语义..
  • @frunsi - 感谢您的提示 ;)

标签: c++ exception visual-studio-2003


【解决方案1】:

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

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

【讨论】:

  • 如果父类编译成库而没有开启RTTI,你又不能重新编译,那你可能倒霉了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多