将c ++接口实例化为子类 [英] Instantiating c++ interface as a child class
问题描述
我有一个界面,让我们称之为生物
,他有虚拟函数,使它是抽象的。
I have an interface, let's call it Creature
, who has virtual functions that cause it to be abstract.
我有这个界面的子类,例如 Dog
, Cat
和 Pig
。
I have child classes of this interface such as Dog
, Cat
, and Pig
.
编译器似乎不喜欢下面的行,因为无法声明变量 thing
的抽象类型生物
。
The compiler doesn't seem to like the following line due to not being able to declare variable thing
to be of abstract type Creature
.
Creature thing = Dog();
我知道我不能实例化接口等,但这只是一个 Dog
被声明为 Creature
。
I know I can't instantiate interfaces and the like, but this is just a Dog
being declared as a Creature
.
我需要一种方法让所有的孩子都有一个声明工作(例如,可以把 Dog()
, Cat()
或 Pig()
其中 Dog $ c>在上面的行)。
I need some way of having one declaration work for all the children (i.e., being able to put Dog()
, Cat()
, or Pig()
where Dog()
is in the line above).
这可以在c ++中完成,还是我完全错误地使用继承和接口?
Can this be done in c++ or am I misusing inheritance and interfaces completely?
推荐答案
对象类型本身在C ++中不是多态的。您给定的行声明了一个 Creature
对象,然后尝试使用 Dog
对象初始化它。如果 Creature
不是抽象的,这将导致切片 - thing
不会是 Dog
,它只是一个生物
。因为它是抽象的,你根本不能有一个 Creature
对象。
Object types themselves are not polymorphic in C++. The line you've given declares a Creature
object and then attempts to initialise it with a Dog
object. If Creature
weren't abstract, this would result in slicing - thing
wouldn't be a Dog
any more, it would just be a Creature
. Since it is abstract, you simply can't have a Creature
object anyway.
你需要使用指针或多态行为的参考。考虑例如:
You need to use pointers or references for polymorphic behaviour. Consider for example:
Creature* thing = new Dog();
现在可以取消引用 thing
作为 Creature
,即使它的动态类型是 Dog
。但是,通常不推荐使用这样的原始指针,因为您必须手动确保对象 delete
d。所有权可能变得混乱。你最好的办法是把它放在一个聪明的指针,如:
You can now dereference thing
and use it as a Creature
, even though it's dynamic type is Dog
. However, using raw pointers like this is usually not recommended, as you have to manually ensure that the object is delete
d at some point. The ownership can become confusing. Your best bet is to put it in a smart pointer, such as:
std::unique_ptr<Creature> thing(new Dog()); // or std::make_unique when we have it
在这里,我演示了 std :: unique_ptr
,但是智能指针的选择将取决于该对象的所有权语义。一个常见的替代方案是 std :: shared_ptr
。
Here, I've demonstrated std::unique_ptr
, but the choice of smart pointer will depend on the ownership semantics for that object. A common alternative is std::shared_ptr
.
要显示引用的多态性:
Dog dog;
Creature& thing = dog;
// Can now use dog as a Creature
这篇关于将c ++接口实例化为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!