简体   繁体   English

抽象类c ++的对象作为函数的参数

[英]object of an abstract class c++ as a parameter to a function

I have the following code: 我有以下代码:

class Region {
public:
    virtual Region* clone() const = 0;
    virtual ~Region() {}
    bool contains(double x, double y) const = 0;
}

class UnionRegion : public Region {
    shared_ptr<Region> r1;
    shared_ptr<Region> r2;
public:
    UnionRegion(const Region& r1, const Region& r2) :
           r1(r1.clone()), r2(r2.clone()) {}
    .
    .
    .
}

Region is an abstract class. Region是一个抽象类。 I do not understand how the ctor of UnionRegion can receive an object of type Region , because how can we create an object of an abstract class? 我不明白UnionRegion的ctor如何接收Region类型的对象,因为我们如何创建抽象类的对象?

Also what is the point of holding a shared_ptr to Region ? 另外,将shared_ptr保留到Region什么意义? I understand that because Region is abstract we need a pointer, but Region doesn't even have private members, so basically I can do nothing with that pointer. 我知道,因为Region是抽象的,我们需要一个指针,但是Region甚至没有私有成员,因此基本上我无法使用该指针。

Thanks! 谢谢!

Region is an abstract class, but it is never instantiated. Region是一个抽象类,但从未实例化。 A reference to const Region binds to an object of any subclass of Region (much as a pointer to const Region would). 所述的参考const Region结合的任何亚类的一个对象Region (就像一个指针const Region会)。 So UnionRegion 's constructor takes references to any two objects that are subclasses of Region . 因此, UnionRegion的构造函数将引用作为Region子类的任何两个对象。

Since UnionRegion inherits from Region the UnionRegion(const Region& r1, const Region& r2) can be called with either other UnionRegion parameters or any other class type which inherits from Region . 由于UnionRegionRegion继承,因此可以使用其他UnionRegion参数或从Region继承的任何其他类类型来调用UnionRegion(const Region& r1, const Region& r2) Since this is a constructor I assume there might be also some other class type which inherits from Region and is used to construct UnionRegion . 由于这是一个构造函数,因此我假设可能还有其他一些类类型,这些类从Region继承并用于构造UnionRegion

how can we create an object of an abstract class? 我们如何创建抽象类的对象?

You can not create an object of an abstract class, you can only use abstract class reference/pointer which refer to derived concrete class objects. 不能创建抽象类的对象,只能使用抽象类引用/指针来引用派生的具体类对象。

what is the point of holding a shared_ptr to Region? 将shared_ptr保留到Region有什么意义?

If you want a class member which its concrete type is unknown, yo have to use pointer or reference to hold it. 如果要使用其具体类型未知的类成员,则必须使用指针或引用来保存它。 Then later you can invoke override virtual functions to have polymorphism actions. 然后,您可以调用覆盖虚拟函数以具有多态操作。

The one which need to negotiate is: why your UnionRegion which is a derived type need to hold a pointer(shared_ptr) to its base? 需要协商的是:为什么作为派生类型的UnionRegion需要持有指向其基址的指针(shared_ptr)? It's more like design behavior. 它更像是设计行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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