ksa*_*usi 2 c++ virtual inheritance casting
我想知道在继承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;
}
Run Code Online (Sandbox Code Playgroud)
所以基本上,我知道我的狗将吃的动物只是其他狗(在所有情况下,不仅仅是在这个具体的例子中).但是,我继承自纯粹的虚拟类Animal,它要求我使用Animal参数定义函数.
我知道有一个参数作为Animal导致函数Dog :: Eat认为参数是Animal而不是Dog.但是,考虑到对象的数据仍然存在,我很确定有一种方法可以建立(投射等)动物作为狗,我只是不知道我是怎样的不太确定如何搜索.
所以我想知道我会怎么做.我敢肯定,你可以使用动态转换或重新解释投,但我是你通常要尽量少用这些铸件的印象,如果你能.我是C++中面向对象的新手,因为我以前主要只使用C.
你确实可以施展它(假设你打算Dog公开衍生出来Animal); 但你必须投射一个引用或指针.你对一个值的强制转换会尝试Dog从Animal传入的内容中创建一个新的; 而且没有合适的转换.
// 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
Run Code Online (Sandbox Code Playgroud)
不要用reinterpret_cast; 这允许各种疯狂的转换,所以很容易做错事.不要使用C风格的演员表(Dog&)a- 它允许更多的转换reinterpret_cast,并且具有微妙且难以搜索的语法.
通常,您根本不需要转换 - 尝试设计基类,以便它暴露您想要使用它执行的所有操作,而无需知道实际的对象类型.