【问题标题】:C++ Casting From Parent to Child After Passing as a Function?作为函数传递后,C ++从父级转换为子级?
【发布时间】:2014-03-25 13:40:19
【问题描述】:

我想知道在从 C++ 中的接口继承时,这(如上标题)是否完全可行。

class Animal
{
   public:
      virtual void Eat(Animal& a) = 0; //Function that attempts to eat an animal.
}

class Dog : Animal
{
   public:
       void Eat(Animal& a);
}

void Dog::Eat(Animal& a)
{
    Dog d = (Dog) a;
    // Do something.
}

int main()
{
   Dog dog1 = Dog();
   Dog dog2 = Dog();

   dog1.Eat(dog2);
   return;
}

所以基本上,我知道我的狗要吃的动物只是其他狗(在所有情况下,不仅仅是在这个特定的例子中)。但是,我是从一个纯虚拟类 Animal 继承的,这需要我使用 Animal 参数定义函数。

我知道将参数设置为 Animal 会导致函数 Dog::Eat 认为参数是 Animal 而不是 Dog。但是,考虑到要表示为 Dog 的对象的数据仍然存在那里,我很确定有一种方法可以将 Animal 建立(演员等)为 Dog,我只是不'不知道如何,我不太确定如何搜索。

所以我想知道我将如何做到这一点。我很确定您可以使用动态转换或重新解释转换,但我的印象是您通常希望尽量减少这些转换的使用如果可以的话。我对 C++ 中的面向对象很陌生,因为我以前主要只使用 C。

【问题讨论】:

  • 狗应该从动物继承。
  • @Namfuak 是的,应该!对此感到抱歉。

标签: c++ inheritance casting virtual


【解决方案1】:

您确实可以转换它(假设您打算将 Dog 公开派生自 Animal);但是您必须强制转换引用或指针。您对一个值的强制转换将尝试从传入的Animal 创建一个新的Dog;并且没有合适的转换。

// safest, if you can't guarantee the type
Dog & d = dynamic_cast<Dog&>(a);  // throws if wrong type
Dog * d = dynamic_cast<Dog*>(&a); // gives null if wrong type

// fastest, if you can guarantee the type
Dog & d = static_cast<Dog&>(a);   // goes horribly wrong if wrong type

不要使用reinterpret_cast;这允许各种疯狂的转换,所以很容易做错事。也不要使用 C 样式转换 (Dog&amp;)a - 它允许比 reinterpret_cast 更多的转换,并且语法微妙且难以搜索。

一般来说,您根本不需要强制转换 - 尝试设计基类,以便它公开您想用它做的所有事情,而无需知道实际的对象类型。

【讨论】:

  • 谢谢!我认为这更像是一个设计缺陷。
猜你喜欢
  • 1970-01-01
  • 2019-12-04
  • 2015-10-20
  • 2023-01-30
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多